Searching, Sorting & Selection


Answer & solution
Answer: Use a balanced search tree of distinct values and counts, then inorder expansion: O(n log(k+1)) time and O(k) auxiliary space; worst-case optimal in the comparison model. (no official key was published)
Maintain one node per distinct key in a balanced binary search tree, storing a frequency counter. Unlike a simple unbalanced BST, an AVL or red-black tree guarantees height O(log(d+1)) when d distinct values have been encountered. The algorithm discovers k automatically.
SORT_FEW_DISTINCT(A):
T := empty balanced search tree
for x in A:
node := FIND(T,x)
if node exists: node.count := node.count + 1
else: INSERT_BALANCED(T, key=x, count=1)
output := empty sequence
for node in INORDER(T):
repeat node.count times: append node.key to output
return outputAfter each insertion, the tree contains exactly the distinct input values seen so far, with their correct multiplicities. Inorder traversal visits keys in increasing order, and expanding each count preserves all occurrences. Thus the output is a sorted permutation of the input.
Each of n updates costs O(log(k+1)); inorder traversal costs O(k), and emitting n values costs O(n). Total time is O(n log(k+1)), commonly written O(n log k) for k≥2. The +1 handles k=1, where the algorithm is linear. Auxiliary tree storage is O(k), excluding the n-element output; an array can be overwritten during the final traversal if the input need not be retained.
For worst-case comparison optimality at fixed n and k, consider balanced multiplicities among k ordered values. There are n!/(n1!…nk!) distinguishable orderings, where each ni is approximately n/k. A constant-branching comparison decision tree requires Ω(log(n!/(n1!…nk!)))=Ω(n log k) comparisons in the worst case for k≥2. Reading or writing the input/output also costs Ω(n), giving Ω(n log(k+1)) overall. This is a worst-case statement over multiplicities, not a claim of distribution-sensitive optimality for every frequency pattern. With bounded integer keys, counting/radix methods may bypass the comparison lower bound; without a key-universe assumption they are not a general replacement.