Why Sorting Everything Wastes Time and Memory
Whenever an interview problem asks for "top K frequent," "Kth largest in a stream," or "closest K points," sorting the full input in works only as a naive baseline. As noted in the Ace Hired roadmap comparison, heap and priority-queue questions are among the first topics where Blind 75 feels light while modern loops test variations relentlessly.
I reach for a heap whenever I only need repeated access to the extreme boundary (minimum or maximum) of a changing set, rather than full total order. In Python, `heapq` implements zero-indexed binary min-heaps directly on top of list, giving heappush and heappop, heapify, and root inspection at heap[0].
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Intuition Across the Three Heap Shapes
1. The counter-intuitive top-K rule: min-heap for largest
Candidates routinely pick a max-heap to find the K largest elements. That forces you to push all elements ( space, pushes or heapify plus pops).
If or data arrives as an unbounded stream, invert the heap: maintain a min-heap capped at size . The root heap[0] is the smallest element among the top seen so far, acting as a gatekeeper. Any incoming element smaller than or equal to heap[0] is ignored immediately; any larger incoming element replaces heap[0] via heapq.heapreplace. Memory stays fixed at .
2. Two heaps for streaming medians
Finding a median requires splitting sorted values at the middle. Maintain a max-heap low holding the smaller half and a min-heap high holding the larger half, enforcing len(low) == len(high) or len(low) == len(high) + 1.
Notice one subtle Python runtime nuance: even though Python 3.14 added heapify_max and heappush_max, most production interview judges still run Python 3.11 or 3.12. Negating numbers (-x) when pushing into low remains portable everywhere and avoids version surprises.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
To keep max(low) <= min(high) cleanly without brittle if/else trees, route every new value through the opposite heap: push to low and pop its maximum to high, then rebalance if len(high) > len(low) by moving high[0] back to low.
3. K-way merge with tie-breakers
When merging sorted lists or iterables, push only the current head of each non-empty list as (value, list_index, element_index) (or use a monotonically increasing tie-breaker counter if nodes cannot be compared). Because list_index is unique across active lists, Python never tries to compare two list objects or tree nodes when value ties.
One extra pattern worth keeping in reserve is lazy deletion with heaps, covered cleanly in the Python `heapq` priority queue notes. Because standard binary heaps do not support deletion of arbitrary interior items (such as an outgoing element leaving a sliding window median, or an older stale distance inside Dijkstra's algorithm), record deletions in a dictionary or invalid count map, and discard stale roots at the top of the heap (while heap and invalid[heap[0]] > 0: ...) before reading the current extremum. Since each element is pushed once and lazily discarded at most once, amortized runtime stays per update. Also note that Python's built-in heapq.nlargest(k, nums) is crisp in production code when is small, though interviews normally ask you to implement the bounded loop directly so the invariant is explicit.
Working Python Code
Here are all three tested patterns: kth_largest via bounded min-heap, MedianTracker via negated two-heap rebalancing, and merge_k_sorted via index-keyed heapq.
import heapq
def kth_largest(nums: list[int], k: int) -> int:
min_heap: list[int] = []
for x in nums:
if len(min_heap) < k:
heapq.heappush(min_heap, x)
elif x > min_heap[0]:
heapq.heapreplace(min_heap, x)
return min_heap[0]
class MedianTracker:
def __init__(self) -> None:
self.low: list[int] = [] # negated max-heap
self.high: list[int] = [] # min-heap
def add_num(self, num: int) -> None:
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self) -> float:
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2.0
def merge_k_sorted(lists: list[list[int]]) -> list[int]:
heap: list[tuple[int, int, int]] = []
for list_idx, arr in enumerate(lists):
if arr:
heapq.heappush(heap, (arr[0], list_idx, 0))
merged: list[int] = []
while heap:
val, list_idx, elem_idx = heapq.heappop(heap)
merged.append(val)
nxt = elem_idx + 1
if nxt < len(lists[list_idx]):
heapq.heappush(heap, (lists[list_idx][nxt], list_idx, nxt))
return merged
if __name__ == "__main__":
assert kth_largest([3, 2, 1, 5, 6, 4], 2) == 5
tracker = MedianTracker()
medians = []
for v in (5, 2, 9, 1, 7):
tracker.add_num(v)
medians.append(tracker.median())
assert medians == [5.0, 3.5, 5.0, 3.5, 5.0]
assert merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]) == [1, 1, 2, 3, 4, 4, 5, 6]
print("kth_largest:", kth_largest([3, 2, 1, 5, 6, 4], 2))
print("medians:", medians)
print("merged:", merge_k_sorted([[1, 4, 5], [1, 3, 4], [2, 6]]))Running this script produces:
kth_largest: 5
medians: [5.0, 3.5, 5.0, 3.5, 5.0]
merged: [1, 1, 2, 3, 4, 4, 5, 6]Complexity Analysis
| Heap Pattern | Time Complexity | Extra Space | Notes |
|---|---|---|---|
Bounded min-heap (kth_largest) | Ideal for streams and small | ||
heapify + pops | Faster when array is static and is tiny | ||
Two-heap add_num / median | / | Rebalance uses at most 3 heap operations | |
| K-way merge ( total items, lists) | Heap never holds more than frontier items |
As documented in Python built-in time complexity, sorting a full array takes comparisons, so whenever , keeping heap height at saves both CPU work and peak allocation.
Common Mistakes and When I Skip Heaps
Four bugs appear repeatedly in heap interviews:
- Pushing unorderable tie-breakers (`(val, node)`): In Python, if two items have equal
val, tuple comparison comparesnode < other_nodeand raisesTypeErroronListNodeobjects. Always insert an integer counter or index as the second element. - Popping from an empty heap: Check
if min_heap:before callingheappopor indexingmin_heap[0]. - Using `heappush` then `heappop` separately:
heapreplace(pop then push) andheappushpop(push then pop) perform a single sift pass, making fixed-size heaps faster and cleaner. - Forgetting to un-negate on `low[0]`: When inspecting a negated max-heap, forgetting the unary minus corrupts both balance comparisons and median formulas.
I skip heaps in two scenarios: when (a single linear min() or max() scan in space wins easily), and when a bounded small integer domain (like character frequencies or bounded values in ) lets bucket sort solve top-K in pure linear time without logarithmic overhead.
Practice Problems
Apply bounded heaps and dual-heap balancing on these two interview staples:
- Kth Largest Element in an Array: Implement the size- min-heap solution and compare its runtime against Quickselect when duplicates dominate.
- Find Median from Data Stream: Implement
MedianTrackerusing the push-pop-rebalance invariant and test odd, even, and negative inputs.
