AlgoViz

Two heaps

medium 22 min

The two heaps pattern keeps a max-heap for the smaller half of the values and a min-heap for the larger half.

See it run

A max-heap holds the smaller half and a min-heap holds the larger half, so the median always sits on the two roots.

Operations

add (route, then rebalance)

Stream 41, 35, 62, 4, 97, 108 into a MedianFinder. Each value is routed by comparing it with the top of low, then the sizes are repaired.

Step 1 of 12

Two empty heaps

∅low empty∅high empty

low · max-heap · 0

empty

high · min-heap · 0

empty

median

empty

invariants: max(low) ≤ min(high), 0 ≤ |low| − |high| ≤ 1

low is a max-heap for the smaller half (Python stores it negated), high is a min-heap for the larger half. Rule of thumb: low may hold one extra value, never high.

Step 1: Two empty heaps

import heapqclass MedianFinder:    def __init__(self):        self.low = []    # max-heap of the smaller half (stored negated)        self.high = []   # min-heap of the larger half    def add(self, x):        if not self.low or x <= -self.low[0]:            heapq.heappush(self.low, -x)     # belongs to the smaller half        else:            heapq.heappush(self.high, x)     # belongs to the larger half        self.rebalance()    def rebalance(self):        if len(self.low) > len(self.high) + 1:            heapq.heappush(self.high, -heapq.heappop(self.low))        elif len(self.high) > len(self.low):            heapq.heappush(self.low, -heapq.heappop(self.high))    def median(self):        if len(self.low) > len(self.high):            return -self.low[0]        return (-self.low[0] + self.high[0]) / 2
Time
O(log n)
Space
O(n) total
sort after each add
O(n log n)
insort into a list
O(n) shift

Compare against the top of low to route, then fix sizes with at most one move. Two rules, and both invariants hold after every add.

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Reading low's top without un-negating

    critical

    heapq is a min-heap, so low stores -x. low[0] is the negative of the largest small value; forgetting the minus flips the median's sign.

    Wrong
    return low[0]                      # -41, not 41
    Right
    return -low[0]                     # 41
  • Balancing sizes without routing by value

    critical

    Pushing every value into whichever heap is smaller keeps the counts even but breaks max(low) ≤ min(high), so the roots are not the middle values.

    Wrong
    if len(low) <= len(high):    heapq.heappush(low, -x)        # value never comparedelse:    heapq.heappush(high, x)
    Right
    if not low or x <= -low[0]:    heapq.heappush(low, -x)else:    heapq.heappush(high, x)rebalance()
  • A rebalance condition that lets high win

    major

    median() assumes low holds the extra value on an odd count. Moving whenever low is merely bigger leaves high one bigger, and low[0] is then not the median.

    Wrong
    if len(low) > len(high):            # moves on every odd count    heapq.heappush(high, -heapq.heappop(low))
    Right
    if len(low) > len(high) + 1:    heapq.heappush(high, -heapq.heappop(low))elif len(high) > len(low):    heapq.heappush(low, -heapq.heappop(high))
  • Floor division for the even median

    major

    // rounds down: (41 + 62) // 2 is 51, not 51.5, and with negatives (-3 + 0) // 2 is -2, not -1.5.

    Wrong
    return (-low[0] + high[0]) // 2
    Right
    return (-low[0] + high[0]) / 2
  • Removing from the middle of a heap

    critical

    list.remove costs O(k) and leaves the list out of heap order, so later roots are wrong. In a sliding window, mark the value as gone and pop it when it reaches a root.

    Wrong
    low.remove(-y)                     # heap order broken
    Right
    gone[y] = gone.get(y, 0) + 1       # lazy deletelive[0] -= 1prune(low, -1)                     # only pops dead roots
  • Popping an empty ready heap in IPO

    minor

    If no locked project is affordable, ready is empty and heappop raises IndexError. Stop early: capital cannot grow any more.

    Wrong
    w += -heapq.heappop(ready)          # IndexError when empty
    Right
    if not ready:    breakw += -heapq.heappop(ready)

Interview tips

  • How to explain it

    • A max-heap for the smaller half, a min-heap for the larger half.
    • Order: max(low) ≤ min(high). Balance: low has the same size as high or one more.
    • add is O(log n), median is O(1), space is O(n).
  • Spot it in the wild

    • Median or percentile of a growing stream.
    • Median of every sliding window: add lazy deletion.
    • Pick the best item among those unlocked so far (IPO, meeting rooms III): one heap per key.
  • Memory tricks

    • SPLIT: Small half in a max-heap, Push to the right heap, Large half in a min-heap, Invariant sizes differ by at most 1, Tops give the median.
    • Two piles of cards facing each other: the top cards meet in the middle.
    • Route by value, repair by size.
  • Watch out

    • Negate on the way in and on the way out of low.
    • Use / 2 for the even median.
    • With lazy deletion, balance on live counters, not len().