Learn / Heaps and priority queues

Two heaps

To track the median of a growing set, keep the smaller half in a max heap and the larger half in a min heap, with sizes equal or the lower half one bigger. The median is the top of the lower half, or the average of both tops. Each insert is O(log n) and each median O(1).

How to recognise it

  • You need the median, or another middle value, of a stream.
  • The data splits into a lower part and an upper part, and you need the boundary between them.
  • Values arrive and leave while the middle must stay available.

The two halves

addNum(x):
    push x into low (max heap)
    move low's top into high (min heap)     # keeps low <= high
    if high is bigger than low: move high's top back into low
findMedian():
    if low is bigger: return low.top
    return (low.top + high.top) / 2

The pushes always go through low and then across, so every value in low stays at most every value in high. The last step keeps the sizes balanced. The two tops are the two values next to the middle.

CountMedian
oddtop of low
evenmean of the two tops

Common mistakes

  • Comparing the new value with one top and pushing it straight into one heap, then forgetting to rebalance.
  • Adding two big ints before dividing: use 64-bit or divide as doubles.
  • Python has only a min heap: store negated values for the max heap.

Problems

0 of 1 solved

Check yourself

Which heap holds the smaller half?

The low half has 3 values and the high half 3. What is the median?

After pushing a new value into the low heap, why move its top to the high heap?