Problem 34 · Heaps
Find Median from Data Stream
01Problem
Design a structure supporting add_num(x) and find_median() over a stream of integers.
02Key insight
Two heaps: a max-heap for the lower half and a min-heap for the upper half, kept balanced within one element; the median is read from the tops in O(1).
03Solution
Try it first.
TimeO(log n) add, O(1) median
SpaceO(n)
tests.py · 3 passing
tests.pypython8 lines
mf = MedianFinder()
mf.add_num(1); mf.add_num(2)
assert mf.find_median() == 1.5
mf.add_num(3)
assert mf.find_median() == 2.0
for x in [-5, -5, 100]:
mf.add_num(x)
assert mf.find_median() == 1.504Staff-level follow-up
Unbounded stream across many machines? Exact medians need all data; use mergeable quantile sketches (t-digest, KLL) with bounded error, or bucket counts if the value range is small.