Heaps and top-K
A heap returns the smallest (or largest) item in O(1) and inserts or removes in O(log n); a size-K heap gives top-K in O(n log K) without sorting everything.
How it works
- A binary heap is a tree stored in an array; every parent is ≤ its children.
- Top-K largest: a min-heap of size K; when it passes K, evict the root.
- The root is the weakest candidate, the K-th largest; O(K) memory lets it run on streams.
- K-way merge keeps one head per sorted list; a running median balances two heaps.
- Python's
heapqis a min-heap: negate keys for max, add a counter to break ties.
Check yourself
Answer to mark it learned; your answers aren't scored.
You must return the 100 largest transaction amounts from a stream of 1 billion, on a worker with 1 GB of RAM. Which approach do you pick?
Go deeper
Solve it in Python 10
- Last stone left after smashingeasy
- Farthest rooftop with bricks and laddersmedium
- The k points nearest the originmedium
- The k smallest pair sumsmedium
- Merge many sorted listsmedium
- The k most frequent valuesmedium
- Task order on a single coremedium
- Median after each new numberhard
- Most capital after k projectshard
- Rain trapped on a height maphard
Full explanation
A binary heap is a complete binary tree stored in an array where every parent is ≤ its children (a min-heap). The minimum sits at index 0; push and pop each repair one root-to-leaf path in O(log n). Building a heap from a list is O(n).
The patterns:
- Top-K largest: keep a min-heap of size K. Push each item; when the heap passes K, pop the root. The root is the weakest candidate, the K-th largest. O(n log K) time, O(K) memory, works on a stream.
- K-way merge: push the head of each sorted list; pop the smallest, push its successor. O(N log k).
- Running median: a max-heap for the lower half and a min-heap for the upper half, sizes within one.
- Scheduling: always pop the next task by priority or deadline; Dijkstra does the same (Shortest Paths (BFS, Dijkstra, Bellman-Ford)).
Python's heapq is a min-heap on plain lists: negate keys for a max-heap, or use the _max functions added in Python 3.14.
Code Top-K, k-way merge and a stable priority queue
import heapq
from itertools import count
def top_k(nums, k):
heap = [] # min-heap: the k largest so far
for x in nums:
heapq.heappush(heap, x)
if len(heap) > k:
heapq.heappop(heap) # evict the smallest candidate
return sorted(heap, reverse=True) # heap[0] is the k-th largest
def merge_k(lists):
heap = [(lst[0], i, 0) for i, lst in enumerate(lists) if lst]
heapq.heapify(heap) # O(k)
out = []
while heap:
val, i, j = heapq.heappop(heap) # i breaks ties before payloads
out.append(val)
if j + 1 < len(lists[i]):
heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
return out
class TaskQueue:
def __init__(self):
self.heap, self.seq = [], count() # seq: FIFO among equal priorities
def push(self, priority, task):
heapq.heappush(self.heap, (priority, next(self.seq), task))
def pop(self):
return heapq.heappop(self.heap)[2] # lowest priority number firstReal example
Top K frequent words: assume a log with 1M distinct words and K = 10. Count with a hash map in one pass, then run the 1M (count, word) pairs through a min-heap of 10: ~1M × log₂10 ≈ 3.3M steps and 10 slots of memory. Sorting all pairs costs ~1M × log₂(1M) ≈ 20M steps and a 1M-entry list. The time gain is ~6×; the bigger win is memory, which lets the same code run on a stream.
Trade-offs +3 · −2
+ You gain
- O(n log K) time and O(K) memory: fits streams and data larger than RAM.
- In every standard library: Python
heapq, JavaPriorityQueue, C++priority_queue. - Dynamic: inserts and extractions interleave, unlike a one-off sort.
− You pay
- No fast search or delete of an arbitrary item: O(n) to find it, so use lazy deletion.
- Only the root is ordered; iterating the array is not sorted order.
Use it when
K largest, smallest, closest or most frequent; merging sorted streams or files; 'always process the next cheapest or earliest' (schedulers, Dijkstra, event simulation); a running median.
Avoid it when
K close to n (just sort); the max of a fixed sliding window (Stacks and monotonic stacks, O(n)); a single k-th element on in-memory data (quickselect, average O(n)).
Numbers to know 4
- Push and pop O(log n); peek O(1);
heapifyO(n). - Top-K: O(n log K) time, O(K) space. Full sort: O(n log n) time, O(n) space.
- K-way merge of N total items from k lists: O(N log k).
- Quickselect: average O(n), worst case O(n²).
Common pitfalls 4
- A max-heap of size K for the K largest: you evict the biggest and keep the wrong items.
- Pushing
(priority, obj): on equal priorities Python compares the objects, aTypeErrorif they aren't orderable. Add a counter. - Expecting the heap list to be sorted: only
heap[0]is guaranteed. Sort at the end if order matters. - Merging per-shard top-K lists for a global top-K: an item ranked #11 on every shard can be #1 overall.
Interview questions 3
Answer out loud first, then reveal.
Top-K largest: why a min-heap and not a max-heap?Show answer
The heap holds the candidates, and the root must be the one to evict: the weakest. With a min-heap of size K, each new item either beats the root and replaces it, or is ignored. That's O(n log K) time and O(K) memory, so it works on a stream. A max-heap of all n items also works, O(n + K log n), but needs everything in memory first.
How do you recognize a heap problem, and what are the variants?Show answer
Signals: 'K largest, smallest, closest or most frequent', 'merge sorted…', 'always take the next cheapest', or a median that updates as data arrives. Variants: top-K with a size-K heap, k-way merge with one head per list, two heaps for the median, and a scheduler with lazy deletion. If K is fixed and the data is in memory, I mention quickselect, average O(n), as the alternative.
Top 10 search queries of the day across 100 servers?Show answer
I don't merge each server's local top 10: a query ranked #11 everywhere can have the highest total. I aggregate counts per query first, partitioning by a hash of the query so each partition owns some queries, then take a top-10 heap per partition and merge those small lists. If exact counts are too expensive, a count-min sketch plus a heap of heavy hitters bounds memory at the cost of approximate counts.