Finding the Top K with a Heap
Use the smallest retained value as the threshold for admitting a new candidate.
Core Intuition & How It Works
To find the K largest elements in a stream of n items without sorting everything, maintain a min-heap of size K. Any element larger than the heap’s minimum replaces it, yielding O(n log k) time and O(k) memory.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n log k) |
| Space Complexity | O(k) |
| Topic Chapter | Chapter 8: Heaps & Priority Queues |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Use a min-heap of size K for K largest (and a max-heap of size K for K smallest) so the eviction boundary is always at the root.
Common Pitfalls & Edge Cases
Using a max-heap of size n when k << n, which wastes O(n) memory and O(n + k log n) time on streaming data.
Real-World & Technical Interview Applications
Trending leaderboards, K closest points, top-K frequent queries, and search ranking pipelines.