Data Structures and Algorithms5 min read

Heaps and Top-K Patterns: Bounded Min-Heaps, Two Heaps, and K-Way Merge

Why bounded min-heaps find the K largest items faster than sorting, how two heaps balance running medians, and how Python heapq avoids tuple comparison crashes in K-way merges.

A bounded min-heap of size K finds the K largest elements in O(n log K) time and O(K) memory by keeping the weakest surviving candidate at the root for instant eviction. Combining a max-heap and a min-heap maintains streaming medians in O(log n) per insertion, while K-way merge uses a priority queue keyed by (value, tie_breaker, payload) to merge sorted streams without comparing unorderable objects.

Key takeaways

  • Negate values in Python 3.11 and 3.12 heapq to simulate a max-heap cleanly across judges.
  • Choose size-K heap over full sorting whenever K is much smaller than N or the stream is unbounded.
  • Separate value priority from non-comparable node objects inside heap tuples.

Quick facts

  • Use a min-heap of size K for K-largest queries and a max-heap (negated values) for K-smallest queries.
  • heapq.heapify transforms an existing Python list in-place in O(n) linear time.
  • Two-heap balancing moves elements across heaps via heappushpop rather than manual conditional trees.
  • Including a unique index or sequence counter in heap tuples prevents TypeError when values tie.

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 O(nlog⁡n)O(n \log n) 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 O(log⁡n)O(\log n) heappush and heappop, O(n)O(n) heapify, and O(1)O(1) root inspection at heap[0].

Bounded min-heap top-K architecture and Python array indexing layout
Bounded min-heap top-K architecture and Python array indexing layout

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 nn elements (O(n)O(n) space, O(nlog⁡n)O(n \log n) pushes or O(n+klog⁡n)O(n + k \log n) heapify plus pops).

If k≪nk \ll n or data arrives as an unbounded stream, invert the heap: maintain a min-heap capped at size kk. The root heap[0] is the smallest element among the top kk 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 O(k)O(k).

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.

Two-heap running median trace for stream 5, 2, 9, 1, 7
Two-heap running median trace for stream 5, 2, 9, 1, 7

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 kk 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 O(log⁡n)O(\log n) 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 O(log⁡n)O(\log n) per update. Also note that Python's built-in heapq.nlargest(k, nums) is crisp in production code when kk is small, though interviews normally ask you to implement the bounded loop directly so the O(nlog⁡k)O(n \log k) 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.

PYTHON
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:

TEXT
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 PatternTime ComplexityExtra SpaceNotes
Bounded min-heap (kth_largest)O(nlog⁡k)O(n \log k)O(k)O(k)Ideal for streams and small kk
heapify + kk popsO(n+klog⁡n)O(n + k \log n)O(n)O(n)Faster when array is static and kk is tiny
Two-heap add_num / medianO(log⁡n)O(\log n) / O(1)O(1)O(n)O(n)Rebalance uses at most 3 heap operations
K-way merge (NN total items, kk lists)O(Nlog⁡k)O(N \log k)O(k)O(k)Heap never holds more than kk frontier items

As documented in Python built-in time complexity, sorting a full array takes O(nlog⁡n)O(n \log n) comparisons, so whenever k≪nk \ll n, keeping heap height at log⁡k\log k 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 compares node < other_node and raises TypeError on ListNode objects. Always insert an integer counter or index as the second element.
  • Popping from an empty heap: Check if min_heap: before calling heappop or indexing min_heap[0].
  • Using `heappush` then `heappop` separately: heapreplace (pop then push) and heappushpop (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 k=1k = 1 (a single linear min() or max() scan in O(1)O(1) space wins easily), and when a bounded small integer domain (like character frequencies or bounded values in [0,M][0, M]) lets bucket sort solve top-K in pure O(n)O(n) linear time without logarithmic overhead.

Practice Problems

Apply bounded heaps and dual-heap balancing on these two interview staples:

  1. Kth Largest Element in an Array: Implement the size-kk min-heap solution and compare its runtime against Quickselect when duplicates dominate.
  2. Find Median from Data Stream: Implement MedianTracker using the push-pop-rebalance invariant and test odd, even, and negative inputs.

Sources