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.

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Small half in a max-heap, large half in a min-heap: the median lives on the two tops.

Two piles of cards facing each other, like the two pans of a balance. The left pile holds the smaller cards with its biggest on top, the right pile holds the bigger cards with its smallest on top. Keep the piles level, one card apart at most, and the middle of the deck is always the two top cards.

Cheat sheet

add
O(log n)
findMedian
O(1)
Space
O(n)
Order rule
max of low ≤ min of high
Balance rule
low = high, or high + 1
Odd count
top of low
Even count
average of both tops
Sliding window
lazy deletion, O(n log n)
IPO
min-heap by capital, max-heap by profit

Spot it when you see

  • Median of a data stream, or after every insert.
  • Median of every window of size k.
  • A fixed percentile, such as p90, of a growing list.
  • Choose the best option among those unlocked so far, where unlocking and choosing use different keys.
  • Free and busy resource pools, such as rooms or machines.

Tricks that stick

  • SPLIT: Small half in a max-heap, Push to the correct heap, Large half in a min-heap, Invariant: sizes differ by at most 1, Tops give the median.
  • Route by value, repair by size.
  • Three golden rules: where to add (compare with low's top), balance (one move), read (one or two tops).
  • Negate on the way into low and negate again on the way out.
  • Lazy deletion: mark now, pop when it surfaces.

Do not forget

  • Reading low's top without negating it back.
  • Balancing by size only, without comparing values first.
  • Letting high hold the extra value while median assumes low does.
  • Floor division for the even median.
  • Using len() instead of live counts when values are deleted lazily.
  • Popping an empty heap when nothing is affordable in IPO.