Find median from a data stream
Track the median of a growing stream with two heaps: a max-heap for the lower half, a min-heap for the upper half, kept balanced.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Split the stream into two heaps: a max-heap holding the smaller half of the numbers, and a min-heap holding the larger half. After every insert, rebalance so the two halves differ in size by at most one. The median is then either the top of the larger heap, or the average of both tops when the halves are equal in size.
Code
public class MedianFinder {
private PriorityQueue<int, int> lower = new(Comparer<int>.Create((a, b) => b - a)); // max-heap, smaller half
private PriorityQueue<int, int> upper = new(); // min-heap, larger half
public void AddNum(int num) {
if (lower.Count == 0 || num <= lower.Peek()) lower.Enqueue(num, num);
else upper.Enqueue(num, num);
if (lower.Count > upper.Count + 1) { int m = lower.Dequeue(); upper.Enqueue(m, m); }
else if (upper.Count > lower.Count) { int m = upper.Dequeue(); lower.Enqueue(m, m); }
}
public double FindMedian() =>
lower.Count == upper.Count ? (lower.Peek() + upper.Peek()) / 2.0 : lower.Peek();
}static class MedianFinder {
private final PriorityQueue<Integer> lower = new PriorityQueue<>(Collections.reverseOrder()); // max-heap, smaller half
private final PriorityQueue<Integer> upper = new PriorityQueue<>(); // min-heap, larger half
public void addNum(int num) {
if (lower.isEmpty() || num <= lower.peek()) lower.offer(num);
else upper.offer(num);
if (lower.size() > upper.size() + 1) upper.offer(lower.poll());
else if (upper.size() > lower.size()) lower.offer(upper.poll());
}
public double findMedian() {
return lower.size() == upper.size() ? (lower.peek() + upper.peek()) / 2.0 : lower.peek();
}
}class MedianFinder {
priority_queue<int> lower; // max-heap, smaller half
priority_queue<int, vector<int>, greater<int>> upper; // min-heap, larger half
public:
void addNum(int num) {
if (lower.empty() || num <= lower.top()) lower.push(num);
else upper.push(num);
if (lower.size() > upper.size() + 1) { upper.push(lower.top()); lower.pop(); }
else if (upper.size() > lower.size()) { lower.push(upper.top()); upper.pop(); }
}
double findMedian() {
return lower.size() == upper.size() ? (lower.top() + upper.top()) / 2.0 : lower.top();
}
};import heapq
class MedianFinder:
def __init__(self):
self.lower = [] # max-heap (negated), smaller half
self.upper = [] # min-heap, larger half
def add_num(self, num: int) -> None:
if not self.lower or num <= -self.lower[0]: heapq.heappush(self.lower, -num)
else: heapq.heappush(self.upper, num)
if len(self.lower) > len(self.upper) + 1: heapq.heappush(self.upper, -heapq.heappop(self.lower))
elif len(self.upper) > len(self.lower): heapq.heappush(self.lower, -heapq.heappop(self.upper))
def find_median(self) -> float:
return (-self.lower[0] + self.upper[0]) / 2 if len(self.lower) == len(self.upper) else -self.lower[0]Tips
- Decide which heap a new number belongs to by comparing it with the current top of the lower (max-)heap, not by comparing it with every element.
- Rebalancing moves at most one element between heaps per insertion — it never needs to touch anything deeper.
In the .NET library
Each insert costs O(log n) for the heap push plus a possible O(log n) rebalance, but reading the median back is O(1) — a good trade when the median is read far more often than numbers are inserted.