Home
DSA Patterns
Heap / Priority Queue
Find Median from Data Stream
Find Median from Data Stream
Keep a running median of a stream with two heaps: a max-heap for the smaller half and a min-heap for the larger half.
Problem Understanding
Find Median from Data Stream: design a MedianFinder with addNum(num), which adds a number from a stream, and findMedian(), which returns the median of all numbers added so far — the middle value, or the average of the two middle values when the count is even.
Example: addNum(1), addNum(2), findMedian() → 1.5; addNum(3), findMedian() → 2.
Attempt 1: Keep a Sorted List
Store the numbers in a sorted array and insert each new one in place; the median is then the middle element. findMedian is O(1), but every insertion shifts elements: O(n) per addNum. Re-sorting on every query is worse, O(n log n). The median only ever depends on the two middle values, so the rest of the order is wasted work.
The Intuition: Two Halves, Tops Facing Each Other
Split the numbers into a lower half and an upper half. The median only needs the largest of the lower half and the smallest of the upper half — exactly what a max-heap and a min-heap expose in O(1).
low(max-heap) holds the smaller half;high(min-heap) the larger half.addNum: push ontolow, then movelow's largest tohigh— so everything inlowstays ≤ everything inhigh.- If
highnow has more elements thanlow, movehigh's smallest back.lowkeeps the extra element when the count is odd. findMedian:low's top iflowis bigger, else the average of both tops.
Interactive Walkthrough
addNum EACH VALUE, THEN findMedian
TWO EMPTY HEAPS
stream
0
1
2
low (max-heap) · top →
empty
|
← top · high (min-heap)
empty
low size
0
high size
0
Median
—
low is a max-heap for the smaller half, high a min-heap for the larger half. Both start empty
Next
addNum(1): push 1 onto low
Stream
The stream runs along the top. Below it, low and high are drawn back to back with their tops at the seam, so the median always sits in the middle. Each add shows the push, the crossing to high, and any rebalance; then the median is read from the top or tops.
