34/40
Part 8 of 8 · Follow-upsLearn and do

A running median: two heaps, each holding half the numbers

Numbers arrive one at a time, and after each one you need the median. Keep two heaps:

  • low, a max-heap by negation, holds the smaller half.
  • high, a min-heap, holds the larger half.

Each new number goes to low if it's no bigger than low's top, and to high otherwise. Then one top moves across if it has to, so that low holds as many as high, or one more. The median is low's top, or the mean of the two tops.

low stores each number negated, the max-heap trick for numbers, and high stores them as they are. RunningMedian in the editor follows these rules. Here are its medians on a stream of six:

rm, medians = RunningMedian(), []
for x in [5, 15, 1, 3, 8, 7]:
    rm.add(x)
    medians.append(rm.median())
print(medians)
Predict

Add 5, 15, 1, 3, 8 and 7, one at a time. What's the median after all six?

Pick one to see what it prints.
Pick an answer above to see the rest