Find Median from Data Stream solution explained
Find Median from Data Stream is solved with two heaps: a max-heap for the smaller half of the numbers and a min-heap for the larger half, kept equal in size or with the max-heap one larger. Adding a number costs O(log n), and the median is read from the tops of the heaps in O(1): the max-heap's top when the count is odd, the average of both tops when it is even.
By Evin JohnPublished 8 min read
The problem, restated
Design a small class with two operations. One adds an integer to a growing collection. The other returns the median of all integers added so far: the middle value when the count is odd, and the mean of the two middle values when it is even. Calls can be interleaved in any order, and there may be many more of them than you would want to answer by sorting each time.
| Number added | Everything so far, sorted | Median |
|---|---|---|
| 7 | 7 | 7 |
| 2 | 2, 7 | 4.5 |
| 10 | 2, 7, 10 | 7 |
| 4 | 2, 4, 7, 10 | 5.5 |
| -3 | -3, 2, 4, 7, 10 | 4 |
Useful questions: will the median be asked after every insert or only occasionally, can numbers be negative, are they bounded to a small range, and does the answer need to be a float or is integer division acceptable. Each one can change the best design.
Why it is a favourite design question
This is a data-structure design problem more than an algorithm puzzle. It checks whether you can hold an invariant across many calls, keep two structures in sync, and pick the right trade-off between insert cost and query cost. It also opens naturally into follow-ups about bounded values, sliding windows and approximate answers, which lets the interviewer test how far your reasoning goes.
Follow-ups that come up
- All numbers lie between 0 and 100. Keep 101 counters and walk them to find the middle. Inserts are O(1) and queries O(101), effectively constant.
- Most numbers are in a small range but a few are outliers. Counters for the range, plus a count of values below and above it. The median almost always lands in the counted range.
- Median of only the last w numbers. Now values must also leave. Two heaps with lazy deletion, or a balanced ordered structure, handle the sliding window.
- Percentiles other than the median. Keep the same two-heap split but with a size ratio other than one to one, for example 90 to 10 for the 90th percentile.
- Billions of values, approximate answer allowed. Sketches such as t-digest summarize the distribution in little memory. Describe the idea; nobody expects code.
Baseline: keep the values sorted
Store everything in a sorted list. Binary search finds where a new number belongs in O(log n), but inserting there shifts the elements after it, which is O(n). The median is then a direct index lookup. This is a reasonable first answer and it is clearly correct, which makes it a good reference to test the faster version against.
import bisect
class SortedListMedian:
def __init__(self):
self.values = []
def add(self, num):
bisect.insort(self.values, num) # O(log n) search, O(n) shift
def median(self):
n = len(self.values)
mid = n // 2
if n % 2:
return float(self.values[mid])
return (self.values[mid - 1] + self.values[mid]) / 2Two heaps meeting at the middle
Split the numbers into a lower half and an upper half. The lower half lives in a max-heap, so its largest value is on top. The upper half lives in a min-heap, so its smallest value is on top. Those two tops are the values on either side of the middle. Keep two rules: every value in low is no larger than every value in high, and low holds the same number of values as high or exactly one more. With those rules, the median is low's top for an odd count, and the mean of both tops for an even count.
import heapq
class MedianFinder:
def __init__(self):
self.low = [] # smaller half, max-heap via negated values
self.high = [] # larger half, plain min-heap
def add(self, num):
heapq.heappush(self.low, -num)
# Send the largest of the small half across, so low never exceeds high
heapq.heappush(self.high, -heapq.heappop(self.low))
# Keep low the same size as high, or one bigger
if len(self.high) > len(self.low):
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self):
if len(self.low) > len(self.high):
return float(-self.low[0])
return (-self.low[0] + self.high[0]) / 2This version never compares the new number with anything itself. It always enters low, the largest value of low moves to high, and if high is now bigger, its smallest value moves back. That costs up to three heap operations per insert, still O(log n), and it keeps both rules without any branching on the value. Python's heapq is a min-heap, so low stores negated numbers.
#include <functional>
#include <queue>
#include <vector>
class MedianFinder {
std::priority_queue<int> low; // max-heap: the smaller half
std::priority_queue<int, std::vector<int>, std::greater<int>> high; // min-heap: the larger half
public:
void add(int num) {
if (low.empty() || num <= low.top()) low.push(num);
else high.push(num);
// Rebalance so that low holds as many values as high, or one more
if (low.size() > high.size() + 1) {
high.push(low.top());
low.pop();
} else if (high.size() > low.size()) {
low.push(high.top());
high.pop();
}
}
double median() const {
if (low.size() > high.size()) return low.top();
// Add as doubles so two large ints cannot overflow
return (static_cast<double>(low.top()) + high.top()) / 2.0;
}
};The C++ version takes the other common route: compare the new number with low's top to choose a side, then move one element if the sizes drift apart. It does fewer heap operations per insert. The cast to double before adding matters: two large ints summed as ints can overflow, and the test inputs for this page included values near both ends of the 32-bit range.
Costs
| Design | Add | Median | Space |
|---|---|---|---|
| Unsorted list, sort on every query | O(1) | O(n log n) | O(n) |
| Sorted list with binary insert | O(n) | O(1) | O(n) |
| Two heaps | O(log n) | O(1) | O(n) |
| Counters for a bounded range r | O(1) | O(r) | O(r) |
Test cases
- Exactly one number: the median is that number.
- Two numbers: the median is their mean, which may not be an integer.
- Numbers that arrive in increasing order, then in decreasing order. Both push everything toward one heap and test the rebalancing.
- Repeated values, including a stream of one value only.
- Negative numbers, and in C++ or Java, values near the integer limits.
Typical bugs
- Balancing the sizes but not the order, so a large value sits in low while a smaller one sits in high.
- Letting high grow larger than low, then reading the wrong top for an odd count.
- Integer division for the even case, returning 5 instead of 5.5.
- Forgetting to negate when reading low's top in Python.
- Summing two ints before converting to a floating type in C++ or Java.
Talking through the design
Fictional example
- Candidate
- The median only depends on the values right around the middle. So I'll keep the lower half in a max-heap and the upper half in a min-heap, and the two tops are the middle values.
- Candidate
- Two rules: everything in the low heap is at most everything in the high heap, and low is the same size as high or one bigger. Then the median is low's top when the count is odd, and the average of both tops when it's even.
- Candidate
- Each add is a few heap operations, so log n, and the median is constant time.
- Interviewer
- What if every value is between 0 and 100?
- Candidate
- Then I'd skip the heaps and keep 101 counters. Adding is constant, and finding the middle is a walk over 101 slots.
Keep practicing with
Single heaps that stay at a fixed size appear in Kth Largest Element in an Array and K Closest Points to Origin. Task Scheduler pairs a heap with a queue, a similar two-structure design. If you want to switch to recursion, Subsets and Combination Sum are the next backtracking steps. Another design question with an O(1) contract is LRU Cache.
Natively during practice
Design questions like this one reward talking before typing. Natively, on Mac or Windows, can transcribe a practice round with a friend on a call, and its Brainstorm action can list alternative designs, such as counters for bounded values, from the problem text or a screenshot. Saved sessions stay searchable on your computer, so you can return to the invariant you stated. Read about Natively for coding interviews.
Questions people ask
How do two heaps find the median of a stream?
A max-heap holds the smaller half and a min-heap the larger half. Keep every low value at most every high value, and keep the low heap equal in size or one larger. The median is low's top, or the mean of both tops when the count is even.
What is the time complexity of Find Median from Data Stream?
With two heaps, adding a number is O(log n) and reading the median is O(1). A sorted list gives O(1) median but O(n) inserts because elements shift.
What if all numbers are in a small range?
Use an array of counters, one per possible value. Inserts become O(1) and a median query walks the counters, which is constant time for a fixed range.
Why does the median need a double?
With an even count the median is the mean of two middle values, which may be a fraction such as 5.5. Convert to a floating type before adding, so large integers cannot overflow.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
