"Top-K" problems ask for the largest, smallest, or most frequent items in a dataset. Heaps solve them cleanly in time and space — usually better than sorting all items in .
Top-K largest
Use a min-heap of size . Scan the data; for each element, if the heap has fewer than items, push. Otherwise, if the new element is larger than the heap's minimum, pop the minimum and push the new one. At the end, the heap holds the top .
Why a min-heap when we want the largest? Because we keep evicting the smallest of our current "top " candidates — the min is exactly what we need cheap access to.
Top-K smallest
Mirror image: use a max-heap of size . Evict the max when a smaller element appears.
Top-K frequent
Count occurrences (hash map). Then run top-K largest on the count values, with heap entries being (count, item) pairs. — much better than if .
Streaming top-K
When the data is too large to fit in memory or arrives over time, the heap-of-size- pattern naturally extends: you maintain the heap as new items arrive, with amortized cost per item.
Quickselect alternative
For static data, quickselect finds the -th largest in expected time (worst case ). Pivot-and-partition like quicksort, but recurse only on the side containing the -th rank. Faster than the heap approach when you don't care about the order of the top .