Algo-Sim › Heaps & Priority Queues
Find Median from Data Stream
Hard · Heaps & Priority Queues · step through it in Java, Python and C++ on your own input
Support addNum and findMedian on a growing stream. Two heaps keep the smaller and larger halves, so the median is always at their tops.
Problem
Design a class that receives integers one at a time with addNum(num) and can report, at any moment, the median of everything added so far with findMedian(). With an even count, the median is the mean of the two middle values.
Constraints
- -10⁵ ≤ num ≤ 10⁵
- findMedian is only called after at least one addNum
- Up to 5 · 10⁴ calls in total
Edge cases to test
- One number
- Even count: the mean of the two middles
- All numbers equal
Follow-up questions
- What if all numbers are in 0..100?
- Keep 101 counts and walk them to the middle: O(1) add, O(100) median.
- What if you need the median of a sliding window?
- Two heaps with lazy deletion, or a sorted multiset: O(log k) per step (LC 480).
Solution
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;
}
}Python
import heapq
class MedianFinder:
def __init__(self):
self.low = [] # max-heap: values are stored negated
self.high = [] # min-heap
def addNum(self, num):
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):
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2C++
#include <bits/stdc++.h>
using namespace std;
class MedianFinder {
public:
priority_queue<int> low;
priority_queue<int, vector<int>, greater<int>> high;
void addNum(int num) {
low.push(num);
high.push(low.top());
low.pop();
if (int(high.size()) > int(low.size())) {
low.push(high.top());
high.pop();
}
}
double findMedian() {
if (int(low.size()) > int(high.size()))
return low.top();
return (low.top() + high.top()) / 2.0;
}
};
More Heaps & Priority Queues problems
- Kth Largest Element in an Array (Medium)
- Kth Largest Element in a Stream (Easy)
- Merge K Sorted Lists (Hard)
- Find K Pairs with Smallest Sums (Medium)
- Heap Sort (Build Heap + Sift Down) (Medium)
- Last Stone Weight (Easy)
- K Closest Points to Origin (Medium)
- Top K Frequent Words (Medium)
- Reorganize String (Medium)
- IPO (Hard)