Home
DSA Patterns
Heap / Priority Queue
Find Median from Data Stream
Find Median from Data Stream (LeetCode 295)
Find Median from Data Stream (LeetCode 295): 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.
Find Median from Data Stream Visualization
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.
Find Median from Data Stream Dry Run
Stream: 1, 2, 3, with findMedian() after each add
| Add | After push → move → rebalance | low |
high |
Median |
|---|---|---|---|---|
| 1 | push 1, move 1 to high, high bigger → move 1 back | [1] |
[] |
1 |
| 2 | push 2, move 2 to high, sizes 1 and 1 | [1] |
[2] |
(1 + 2) / 2 = 1.5 |
| 3 | push 3, move 3 to high, high bigger → move 2 back | [2, 1] |
[3] |
2 |
low is shown largest first and high smallest first, so each heap's top is the value next to the other heap.
Find Median from Data Stream LeetCode Solution
Two heaps; JavaScript, TypeScript and C have no standard priority queue, so their snippets include a small binary heap.
Find Median from Data Stream Code
1class Heap {2 constructor(less) { this.a = []; this.less = less; }3 size() { return this.a.length; }4 peek() { return this.a[0]; }5 push(x) {6 const a = this.a; a.push(x);7 for (let i = a.length - 1, p; i > 0 && this.less(a[i], a[(p = (i - 1) >> 1)]); i = p) [a[i], a[p]] = [a[p], a[i]];8 }9 pop() {10 const a = this.a, top = a[0], last = a.pop();11 if (a.length) {12 a[0] = last;13 for (let i = 0; ; ) {14 let m = i;15 for (const c of [2 * i + 1, 2 * i + 2]) if (c < a.length && this.less(a[c], a[m])) m = c;16 if (m === i) break;17 [a[i], a[m]] = [a[m], a[i]];18 i = m;19 }20 }21 return top;22 }23}2425class MedianFinder {26 constructor() {27 this.low = new Heap((x, y) => x > y); // max-heap28 this.high = new Heap((x, y) => x < y); // min-heap29 }30 addNum(num) {31 this.low.push(num);32 this.high.push(this.low.pop());33 if (this.high.size() > this.low.size()) {34 this.low.push(this.high.pop());35 }36 }37 findMedian() {38 if (this.low.size() > this.high.size()) {39 return this.low.peek();40 }41 return (this.low.peek() + this.high.peek()) / 2;42 }43}
Find Median from Data Stream in Python, Java, C++, TypeScript and C
Find Median from Data Stream in Python
class MedianFinder:
def __init__(self):
self.low = [] # max-heap, stored negated
self.high = [] # min-heap
def addNum(self, num: int) -> None:
heapq.heappush(self.low, -num)
heapq.heappush(self.high, -heapq.heappop(self.low))
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def findMedian(self) -> float:
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2Find Median from Data Stream in Java
class MedianFinder {
private final PriorityQueue<Integer> low = new PriorityQueue<>(Collections.reverseOrder());
private final PriorityQueue<Integer> high = new PriorityQueue<>();
public void addNum(int num) {
low.offer(num);
high.offer(low.poll());
if (high.size() > low.size()) {
low.offer(high.poll());
}
}
public double findMedian() {
if (low.size() > high.size()) {
return low.peek();
}
return (low.peek() + high.peek()) / 2.0;
}
}Find Median from Data Stream in C++
class MedianFinder {
priority_queue<int> low; // max-heap
priority_queue<int, vector<int>, greater<int>> high; // min-heap
public:
void addNum(int num) {
low.push(num);
high.push(low.top());
low.pop();
if (high.size() > low.size()) {
low.push(high.top());
high.pop();
}
}
double findMedian() {
if (low.size() > high.size()) {
return low.top();
}
return (low.top() + high.top()) / 2.0;
}
};Find Median from Data Stream in TypeScript
class Heap {
private a: number[] = [];
constructor(private less: (x: number, y: number) => boolean) {}
size(): number { return this.a.length; }
peek(): number { return this.a[0]; }
push(x: number): void {
const a = this.a; a.push(x);
for (let i = a.length - 1, p = 0; i > 0 && this.less(a[i], a[(p = (i - 1) >> 1)]); i = p) [a[i], a[p]] = [a[p], a[i]];
}
pop(): number {
const a = this.a, top = a[0], last = a.pop()!;
if (a.length) {
a[0] = last;
for (let i = 0; ; ) {
let m = i;
for (const c of [2 * i + 1, 2 * i + 2]) if (c < a.length && this.less(a[c], a[m])) m = c;
if (m === i) break;
[a[i], a[m]] = [a[m], a[i]];
i = m;
}
}
return top;
}
}
class MedianFinder {
private low = new Heap((x, y) => x > y); // max-heap
private high = new Heap((x, y) => x < y); // min-heap
addNum(num: number): void {
this.low.push(num);
this.high.push(this.low.pop());
if (this.high.size() > this.low.size()) {
this.low.push(this.high.pop());
}
}
findMedian(): number {
if (this.low.size() > this.high.size()) {
return this.low.peek();
}
return (this.low.peek() + this.high.peek()) / 2;
}
}Find Median from Data Stream in C
typedef struct { int *a; int n; int sign; } Heap; // sign 1: max-heap, -1: min-heap
static int before(Heap *h, int x, int y) { return h->sign * x > h->sign * y; }
static void heapPush(Heap *h, int x) {
int i = h->n++;
h->a[i] = x;
while (i > 0 && before(h, h->a[i], h->a[(i - 1) / 2])) {
int p = (i - 1) / 2, t = h->a[i];
h->a[i] = h->a[p]; h->a[p] = t; i = p;
}
}
static int heapPop(Heap *h) {
int top = h->a[0], i = 0;
h->a[0] = h->a[--h->n];
for (;;) {
int m = i, l = 2 * i + 1, r = l + 1;
if (l < h->n && before(h, h->a[l], h->a[m])) m = l;
if (r < h->n && before(h, h->a[r], h->a[m])) m = r;
if (m == i) break;
int t = h->a[i]; h->a[i] = h->a[m]; h->a[m] = t; i = m;
}
return top;
}
typedef struct { Heap low, high; } MedianFinder;
MedianFinder* medianFinderCreate() {
MedianFinder *f = malloc(sizeof(MedianFinder));
f->low = (Heap){ malloc(50001 * sizeof(int)), 0, 1 }; // max-heap
f->high = (Heap){ malloc(50001 * sizeof(int)), 0, -1 }; // min-heap
return f;
}
void medianFinderAddNum(MedianFinder* f, int num) {
heapPush(&f->low, num);
heapPush(&f->high, heapPop(&f->low));
if (f->high.n > f->low.n) {
heapPush(&f->low, heapPop(&f->high));
}
}
double medianFinderFindMedian(MedianFinder* f) {
if (f->low.n > f->high.n) {
return f->low.a[0];
}
return (f->low.a[0] + f->high.a[0]) / 2.0;
}
void medianFinderFree(MedianFinder* f) {
free(f->low.a); free(f->high.a); free(f);
}Edge Cases & Common Mistakes
- One number: it ends up in
low; the median is that number. - Even count: return a floating-point average,
(a + b) / 2.0, not integer division. - Python has only a min-heap: store
lownegated and negate again when reading. - Skipping the cross-over: pushing straight onto the smaller heap can put a large value in
low, breaking the ordering between the halves. - Follow-ups: if every number is in
[0, 100], a count array of 101 buckets gives O(1) adds; if most are, keep counts for that range and heaps only for outliers.
Summary
Two heaps (a max-heap for the lower half and a min-heap for the upper half) keep the median at the seam between their tops. O(log n) per insert, O(1) per median. It is the two-heaps form of the Heap / Priority Queue pattern.
More practice: DSA interview questions with answers · patterns cheat sheet
