Find Median From Data Stream
Hard · Heaps
Jump to codeSupport adding integers one at a time and finding the median of all values seen. Median queries occur only after at least one insertion; average the middle pair for even counts.
Examples
Example 1
operations = ["addNum","addNum","findMedian","addNum","findMedian"] values = [1,2,0,3,0]
Output: [1.5,2]
Example 2
operations = ["addNum","findMedian"] values = [5,0]
Output: [5]
Constraints
- -100,000 <= num <= 100,000
- findMedian will only be called after adding at least one integer to the data structure.
Function contract
Implement MedianFinder with addNum(num) and findMedian(). Each case starts a new instance. values[i] supplies addNum; its placeholder is ignored for findMedian. Only median queries produce output.
Need a hint?
Keep the smaller half and larger half separately.
Asked in real interviews
Candidates reported versions of Find Median From Data Stream from these company interviews. Some company questions are locked and open with Premium or XP.
- Compute the Median After Each Stream InsertionAmazon
- Maintain the Median of an Integer StreamStackAdapt
- Maintain median of a data streamTrexquant
Solution approach
Use a max-heap for the lower half and a min-heap for the upper half. Insert, move an out-of-order root across if necessary, and rebalance so lower has either equal size or one extra value. The median is lower’s root or the mean of both roots.
Complexity
O(log n) insertion, O(1) median lookup, and O(n) space.
Python reference solution
import heapq
class MedianFinder:
def __init__(self):
self.lower = []
self.upper = []
def addNum(self, num):
heapq.heappush(self.lower, -num)
heapq.heappush(self.upper, -heapq.heappop(self.lower))
if len(self.upper) > len(self.lower):
heapq.heappush(self.lower, -heapq.heappop(self.upper))
def findMedian(self):
if len(self.lower) > len(self.upper):
return -self.lower[0]
return (self.upper[0] - self.lower[0]) / 2
JavaScript solution
// Binary heap: comesBefore(a, b) decides which item has higher priority.
class Heap {
constructor(comesBefore) { this.items = []; this.comesBefore = comesBefore; }
get size() { return this.items.length; }
peek() { return this.items[0]; }
push(value) {
const a = this.items;
a.push(value);
let i = a.length - 1;
while (i > 0) {
const parent = Math.floor((i - 1) / 2);
if (!this.comesBefore(a[i], a[parent])) break;
[a[i], a[parent]] = [a[parent], a[i]];
i = parent;
}
}
pop() {
const a = this.items, result = a[0], last = a.pop();
if (!a.length) return result;
a[0] = last;
let i = 0;
while (2 * i + 1 < a.length) {
let child = 2 * i + 1;
if (child + 1 < a.length && this.comesBefore(a[child + 1], a[child])) child++;
if (!this.comesBefore(a[child], a[i])) break;
[a[i], a[child]] = [a[child], a[i]];
i = child;
}
return result;
}
}
class MedianFinder {
constructor() {
this.lower = new Heap((a, b) => a > b);
this.upper = new Heap((a, b) => a < b);
}
addNum(num) {
this.lower.push(num);
this.upper.push(this.lower.pop());
if (this.upper.size > this.lower.size) this.lower.push(this.upper.pop());
}
findMedian() {
if (this.lower.size > this.upper.size) return this.lower.peek();
return (this.lower.peek() + this.upper.peek()) / 2;
}
}
Java solution
import java.util.*;
class MedianFinder {
private final PriorityQueue<Integer> lower = new PriorityQueue<>(Comparator.reverseOrder());
private final PriorityQueue<Integer> upper = new PriorityQueue<>();
public void addNum(int num) {
lower.add(num);
upper.add(lower.remove());
if (upper.size() > lower.size()) lower.add(upper.remove());
}
public double findMedian() {
if (lower.size() > upper.size()) return lower.peek();
return ((double)lower.peek() + upper.peek()) / 2;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class MedianFinder {
priority_queue<int> lower;
priority_queue<int, vector<int>, greater<int>> upper;
public:
void addNum(int num) {
lower.push(num);
upper.push(lower.top()); lower.pop();
if (upper.size() > lower.size()) {
lower.push(upper.top()); upper.pop();
}
}
double findMedian() {
if (lower.size() > upper.size()) return lower.top();
return ((double)lower.top() + upper.top()) / 2;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 10 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[
[
"addNum",
"addNum",
"findMedian",
"addNum",
"findMedian"
],
[
1,
2,
0,
3,
0
]
][ 1.5, 2 ]
[
[
"addNum",
"findMedian"
],
[
5,
0
]
][ 5 ]
[
[
"addNum",
"addNum",
"addNum",
"findMedian"
],
[
2,
3,
4,
0
]
][ 3 ]
[
[
"addNum",
"addNum",
"findMedian"
],
[
-1,
-2,
0
]
][ -1.5 ]
[
[
"addNum",
"findMedian",
"addNum",
"findMedian",
"addNum",
"findMedian"
],
[
10,
0,
20,
0,
30,
0
]
][ 10, 15, 20 ]
Drafts are saved per language in this browser when storage is available.