Top-K Elements & Scheduling Problems With Heaps / Priority Queues
October 14, 2026 · 6 min read
Any time an interview prompt mentions **Kth largest**, **top K frequent**, **merge K sorted lists**, or **meeting rooms**, your first instinct should be a heap (priority queue).
Why Top-K Largest uses a Min-Heap (not a Max-Heap)
This counterintuitive trick trips people up at first: to find the `K` largest elements in a stream of `N` numbers, keep a **min-heap of size K**. The smallest of your top `K` sits at the root — whenever a bigger number arrives, pop the smallest and push the new one.
import heapq
def top_k_largest(nums, k):
heap = []
for n in nums:
heapq.heappush(heap, n)
if len(heap) > k:
heapq.heappop(heap)
return heapKeeping the heap capped at size `K` keeps memory at `O(k)` and runtime at `O(n log k)` — a huge win when `N` is millions and `K` is 10.