โ Back to the heaps page
Top-K Pattern (bounded heap)
Keep a heap of size k that ejects the weakest member on overflow. Answers "k largest/smallest/most frequent" over huge or streaming data.
What to know
- Counter-intuitive: use a MIN-heap of size k to track the k LARGEST items.
- Memory stays O(k) no matter how big the stream โ the whole point.
- For k close to n, Quickselect on a materialized array is faster.
In the wild: Trending topics, "top 10" dashboards, nearest-neighbor shortlists, alert ranking.
Algorithms to reach for
Top-K elements
O(n log k)K most frequent / largest (LeetCode 347, 215)
K closest points
O(n log k)Bounded max-heap by distance (LeetCode 973)
Streaming kth largest
O(log k) per itemMaintain kth largest as items arrive (LeetCode 703)
Practice problems โ with full guides
Each problem has its own page: progressive hints, how to approach it, and the full solution.