Top-k problem
The top-k problem is: given a list of n elements, find the k largest. It shows up everywhere: the 10 most-read news stories, the 10 best-selling products, the 5 players with the most points. There are 3 ways to solve it: pick the maximum k times, sort everything, or use a heap. The heap one is the most efficient.
The first idea is to pick the maximum, remove it, and repeat k times: each time the list is walked, so it costs O(nk). It works if k is very small, but if k gets close to n it becomes O(n²). The second idea is to sort everything and keep the last k: O(n log n). It always works, but does extra work, because it also sorts the n − k that don't matter.
The efficient way uses a min-heap of size k. The first k elements go in. Then, for each element that follows, it's compared with the root, which is the smallest of the k best. If the new one is larger, the root is removed and the new one goes in. At the end, the heap holds the k largest. Each step costs O(log k), so everything is O(n log k).
Top-k with a heap costs O(n log k): each of the n elements is looked at, and each replacement costs O(log k), because the heap holds k elements. If k is small, log k barely matters and the cost is almost O(n). It also uses only O(k) memory: there's no need to keep the n elements, just the k best.
Top-k with a heap has another advantage: it works for data that arrives bit by bit, a stream. You don't need all the data upfront: every time a new one arrives it's compared with the root and, if it qualifies, the heap is updated. That way, at any moment, the heap holds the k largest seen so far. It's what live rankings use, like a social network's trends.
A very common variant is finding the k most frequent elements, like the 10 most-used words in a text. It's done in 2 steps: first count how many times each one appears with a hash table, in O(n), and then do top-k with a min-heap over those counts. Together the 2 structures solve the problem without sorting everything.
