Heaps & Top-K
Read a little, play a little. No scary maths, and no rush.
The leaderboard that never sorts
A gaming leaderboard tracks 10 million scores but only shows the top 10. Sorting 10 million numbers every time someone scores is madness — and unnecessary, because you only care about the boundary between "in" and "out." A heap maintains exactly that boundary: peek at the smallest in O(1), insert or evict in O(log n).
Top-K largest, the pattern
Keep a min-heap of size K. For each number: push it in; if the heap outgrows K, evict the smallest. At the end, the heap holds precisely the K largest — everything smaller was evicted along the way:
import heapq
def topk(a, k):
h = []
for x in a:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h) # smallest of the hopefuls leaves
return h
Total: O(n log K) instead of O(n log n) for a full sort. When K is 10 and n is 10 million, that's the difference between instant and embarrassing. (Python's heapq is a min-heap; negate values for max-heap behavior.)
Two classics built on it
- Merge K sorted lists: push all K heads into a heap, repeatedly pop the smallest and push its successor. O(N log K) — the backbone of external sorting.
- Running median: a max-heap of the lower half plus a min-heap of the upper half; rebalance on every insert and the median sits at the boundary.
What a heap is underneath
A heap is a binary tree kept "complete" (filled level by level) and stored in a plain array: the children of position i sit at 2i + 1 and 2i + 2. The only rule is that every parent is no larger than its children (for a min-heap), so the smallest item is always at position 0.
- Push: place the new item at the end, then swap it upward while it is smaller than its parent.
- Pop: take the root, move the last item to the top, then swap it downward while it is larger than a child.
Each operation walks one path of a tree of height about log n, which is where O(log n) comes from.
Top-K, traced
Find the 2 largest in [5, 1, 9, 3, 7] with a min-heap of size 2:
- Push 5, push 1: the heap holds {1, 5}.
- Push 9, then evict the smallest (1): {5, 9}.
- Push 3, then evict 3 itself, the smallest: {5, 9}.
- Push 7, then evict 5: {7, 9}.
The answer is 7 and 9. The heap never held more than three items at once.
Shortcuts worth knowing
heapq.nlargest(k, data) and heapq.nsmallest(k, data) do the whole pattern in one call. heapq.heapify(list) turns an existing list into a heap in O(n), faster than pushing items one at a time.
Heap or just sort?
If K is close to n (say, the top 900 of 1,000), sorting is simpler and just as fast. A heap shines when K is small compared with n, or when data arrives as a stream you cannot hold all at once.
Remember this
- "Top K" or "K smallest/largest" in the prompt → reach for a heap, not a sort.
- Min-heap of size K finds K largest; max-heap of size K finds K smallest.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
End of Essential Data Structures
Take the section checkpoint
A short mixed quiz on all 4 chapters, to check you are ready to move on.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue