Find Median from Data Stream
Pattern: Two heaps
Keep the smaller half in a max heap and the larger half in a min heap, with the lower half the same size or one bigger. Each add goes through the low heap, passes its maximum to the high heap, and rebalances. The median is the low top, or the mean of both tops.
The problem
Build MedianFinder with addNum(num) and findMedian(), which returns the median of all numbers added so far (the
mean of the two middle values when the count is even). The tests print medians with one decimal place, such as 1.5
and 2.0; findMedian is only called after at least one add.
Think first
- What do you need to know to find the median?
- How can two heaps hold that?
- How do you keep the two halves the right sizes?
Hints
Brute force, and why it fails
Keep a sorted list and insert in place: O(n) per add.
The key insight
The median depends only on the boundary between the halves, and two heaps keep exactly that boundary on their tops.
Dry run
| low | 1 |
|---|---|
| high | empty |
addNum(1): low gets 1, passes it to high, high is bigger so 1 comes back. low 1, high empty.
The plan
addNum(x): push x to low; push pop(low) to high
if size(high) > size(low): push pop(high) to low
findMedian(): low.top if low is bigger, else (low.top + high.top) / 2
Complexity
- Time
O(log n) addNum, O(1) findMedian- Space
O(n)
Each add does a few heap operations; the median reads two tops.
Edge cases
- One value.
- Negative values.
- Large values: add in 64 bits before halving.
I've built my logic, show the code
Java
import java.util.*;
class MedianFinder {
private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder()); // the smaller half, max on top
private final PriorityQueue<Integer> high = new PriorityQueue<>(); // the larger half, min on top
public void addNum(int num) {
low.add(num);
high.add(low.poll()); // the biggest of the low half moves up
if (high.size() > low.size()) low.add(high.poll()); // keep low the same size or one bigger
}
public double findMedian() {
if (low.size() > high.size()) return low.peek();
return ((long) low.peek() + high.peek()) / 2.0;
}
}C++
class MedianFinder {
public:
priority_queue<int> low; // the smaller half, max on top
priority_queue<int, vector<int>, greater<int>> high; // the larger half, min on top
void addNum(int num) {
low.push(num);
high.push(low.top()); // the biggest of the low half moves up
low.pop();
if (high.size() > low.size()) { low.push(high.top()); high.pop(); } // keep low the same size or one bigger
}
double findMedian() {
if (low.size() > high.size()) return low.top();
return (static_cast<long long>(low.top()) + high.top()) / 2.0;
}
};Python
import heapq
class MedianFinder:
def __init__(self):
self.low = [] # the smaller half, stored negated so the max is on top
self.high = [] # the larger half, min on top
def addNum(self, num: int) -> None:
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low)) # the biggest of the low half moves up
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high)) # keep low the same size or one bigger
def findMedian(self) -> float:
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2Common mistakes
- Integer division when averaging the two tops.
- Letting the halves differ by more than one.