Find Median from Data Stream
Hard
Topics
The median is the middle value in an ordered list; for an even-sized list it is the average of the two middle values. Design a structure that supports a stream of integers. Implement MedianFinder with addNum(num) to add an integer, and findMedian() to return the median of all elements so far. Medians are reported to one decimal place (e.g. 2.0, 1.5).
Example 1
Numbers arrive one at a time and the median can be asked for at any point, over everything seen so far. With an even count it is the average of the middle two, so the answer is not always one of the numbers that were added.
Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"], values = [[],[1],[2],[],[3],[]] Output: [null,null,null,1.5,null,2.0]
Constraints
- -10^5 <= num <= 10^5
- At most 5*10^4 calls to addNum and findMedian.
- findMedian is only called on a non-empty structure.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Keep the lower half of the numbers in a max-heap and the upper half in a min-heap, balanced in size. The median is then either the top of one heap (odd count) or the average of both tops (even count) — all in O(log n) per insert.
Approach
- Push the new value into the max-heap (lower half), then move its top into the min-heap so ordering holds.
- If the min-heap grows larger, move its top back so the max-heap has equal or one more element.
- findMedian returns the max-heap top when the total is odd, else the average of the two tops.
Dry Run
lo is a MAX-heap of the lower half, stored negated. hi is a min-heap of the upper half.
addNum 1 push -1 lo=[-1] hi=[]
move top to hi lo=[] hi=[1]
hi is bigger, move back lo=[-1] hi=[]
addNum 2 push -2 lo=[-2, -1] hi=[]
move top to hi lo=[-1] hi=[2]
sizes equal, no rebalance
findMedian equal sizes, so average the two tops: (1 + 2) / 2 -> 1.5
addNum 3 push -3 lo=[-3, -1] hi=[2]
move top to hi lo=[-1] hi=[2, 3]
hi is bigger, move back lo=[-2, -1] hi=[3]
findMedian lo is bigger, so its top IS the median -> 2.0
Why every add pushes to lo and then immediately moves to hi: that round trip is
what guarantees the number lands in the correct half. Pushing straight to
whichever heap looks right by comparing against a top is where this gets subtly
wrong on the first element.Complexity
- Time — O(log n) per addNum: each insert does a constant number of heap pushes/pops; findMedian is O(1).
- Space — O(n): the two heaps together store every number.
Common Pitfalls
- Rebalance after every insert so the two heaps never differ in size by more than one.
- For even counts, average as a float so 1 and 2 give 1.5, not 1.
Full Solution — all languages
import heapq
class MedianFinder:
def __init__(self):
self.lo = [] # max-heap via negation (lower half)
self.hi = [] # min-heap (upper half)
def addNum(self, num):
heapq.heappush(self.lo, -num)
heapq.heappush(self.hi, -heapq.heappop(self.lo))
if len(self.hi) > len(self.lo):
heapq.heappush(self.lo, -heapq.heappop(self.hi))
def findMedian(self):
if len(self.lo) > len(self.hi):
return float(-self.lo[0])
return (-self.lo[0] + self.hi[0]) / 2.0import java.util.*;
class MedianFinder {
private PriorityQueue<Integer> lo = new PriorityQueue<>(Collections.reverseOrder());
// lower half
private PriorityQueue<Integer> hi = new PriorityQueue<>();
// upper half
public MedianFinder() {
}
public void addNum(int num) {
lo.offer(num);
hi.offer(lo.poll());
if (hi.size() > lo.size()) lo.offer(hi.poll());
}
public double findMedian() {
if (lo.size() > hi.size()) return lo.peek();
return (lo.peek() + hi.peek()) / 2.0;
}
}#include <bits/stdc++.h>
using namespace std;
class MedianFinder {
public: priority_queue<int> lo;
// max-heap (lower half)
priority_queue<int, vector<int>, greater<int>> hi;
// min-heap (upper half)
MedianFinder() {
}
void addNum(int num) {
lo.push(num);
hi.push(lo.top());
lo.pop();
if (hi.size() > lo.size()) {
lo.push(hi.top());
hi.pop();
}
}
double findMedian() {
if (lo.size() > hi.size()) return lo.top();
return (lo.top() + hi.top()) / 2.0;
}
};// JavaScript has no built-in heap, so this keeps a sorted array via
// binary-search insertion. The two-heap approach (see Python/C++/Java) is
// the O(log n) optimum you'd mention in an interview.
class MedianFinder {
constructor() {
this.a = [];
}
addNum(num) {
let lo = 0, hi = this.a.length;
while (lo < hi) {
const m = (lo + hi) >> 1;
if (this.a[m] < num) lo = m + 1;
else hi = m;
}
this.a.splice(lo, 0, num);
}
findMedian() {
const n = this.a.length;
if (n % 2 === 1) return this.a[(n - 1) / 2];
return (this.a[n / 2 - 1] + this.a[n / 2]) / 2;
}
}