295. Find Median from Data Stream
Hard NeetCode 150 ↗ Open on LeetCode Source: Standard solution only
Quick review
- Pattern
- Heap / Priority Queue
- Time
- O(log n) per add, O(1) per query
- Space
- O(n)
Standard Solution (C++)
SummarySupport inserting numbers one by one and querying the median of everything inserted so far at any time.
Approach
Two balanced heaps. A max-heap holds the smaller half, a min-heap holds the larger half.
- On addNum, push into the max-heap, move its top to the min-heap, then rebalance so the max-heap is never smaller than the min-heap.
- The median is the max-heap top when sizes differ, or the average of both tops when equal.
class MedianFinder {
priority_queue<int> lo; // max-heap, smaller half
priority_queue<int, vector<int>, greater<int>> hi; // min-heap, larger half
public:
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;
}
}; Time O(log n) per add, O(1) per query Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
▶ Run it — editable in-browser playground C++
Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.
C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.