AlgoScope

K-th Largest / Smallest

AlgorithmintermediateHeap Operations

Keep a min heap of size k; the root is the k-th largest after scanning everything.

Decision · step 5 of 11K-th Largest: Third largest of nine
325root

5 is larger than the root 1, so 1 can no longer be in the top 3. 1 leaves, 5 takes the root and sinks to its level. The new root 2 is the 3rd largest so far.

Open in the player →or start at step 5

What you will see

Values enter a size-k heap; anything smaller than the root bounces off.

How k-th largest works →

Cost

BestO(n log k)
AverageO(n log k)
WorstO(n log k)
SpaceO(k)

How you work with it here

play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next, try operations in any order.

Screen readers: Nodes announce value, parent and children; each step announces the comparison and whether the value moves up or down.

Reduced motion: Swaps become value crossfades in both the tree and the array view.

Variants

  • K-th Largest Min heap of size k.
  • K-th Smallest Max heap of size k.