Problem overview
The class MedianFinder keeps a growing collection of integers. addNum(num) adds one number, and findMedian() returns the median of everything added so far as a double. The median is the middle value of the sorted numbers, or the mean of the two middle values when the count is even. A number added twice counts twice.
After adding 1 and 2, the median is 1.5. After adding 3 as well, the sorted numbers are [1, 2, 3] and the median is 2. With the stream 5, -3, -3, 10, the medians after each addition are 5, 1, -3 and 1.
The budget is O(log n) for addNum and O(1) for findMedian, with up to 500,000 calls in total.
Approach: two halves, two heaps
The simplest design stores the numbers in a vector and sorts it for every question. That costs O(n log n) per call to findMedian, far too slow. Keeping the vector sorted by inserting each number in place costs O(n) per insertion, because the elements after it must shift.
The median only depends on the middle of the sorted data, so there is no need to keep all of it sorted. Split the numbers into two halves:
low, the smaller half, in a max-heap: its top is the largest of the small numbers;high, the larger half, in a min-heap: its top is the smallest of the large numbers.
Every value in high is at least every value in low, so the two tops are exactly the two numbers next to the middle. The code keeps the halves the same size, or low one bigger. With an odd count, the median is the top of low. With an even count, it is the mean of both tops. Reading a top takes O(1), and each push or pop takes O(log n).
Here is the state after each number of the stream 5, 1, 9, 7, 3:
add 5: low top=5 size=1, high top=none size=0, median=5
add 1: low top=1 size=1, high top=5 size=1, median=3
add 9: low top=5 size=2, high top=9 size=1, median=5
add 7: low top=5 size=2, high top=7 size=2, median=6
add 3: low top=5 size=3, high top=7 size=2, median=5
After the second number, low holds 1 and high holds 5, and the median is their mean, 3. After the fifth number, the sorted numbers are 1, 3, 5, 7, 9: low holds 1, 3 and 5, and high holds 7 and 9, so the median is the top of low, 5.
Step by step
- Declare
lowas apriority_queue<int>. The C++ priority queue is a max-heap by default, which is what the lower half needs. - Declare
highaspriority_queue<int, vector<int>, greater<int>>. The second argument is the container that stores the values, andgreater<int>reverses the order so the smallest value sits on top. - Push the new number into
low. Every number enters the lower half first, whatever its size. The next lines restore the order between the halves. - Move the top of
lowintohigh: pushlow.top(), thenpop. In C++,top()only reads andpop()only removes, so a move takes both. The value that moves is the largest inlow, so everything left inlowis at most as large as it, and it joinshigh. A new number that is bigger than everything inhighmakes this round trip at once and lands inhigh. Either way, every value inhighis still at least every value inlow. - Check the balance. If
highnow holds more values thanlow, the halves are lopsided. - Move the top of
highback intolowin the same way. The halves are the same size again, orlowis one bigger. - In
findMedian, handle the odd count: whenlowholds more values, returnlow.top(). - Handle the even count: the halves have equal size, so return the sum of both tops divided by
2.0.
The solution in C++
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 (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;
}
};
The C++ details worth a closer look:
- Heap direction.
priority_queueputs the largest element on top by default. For a min-heap, pass the container type andgreater<int>. Forgetting the comparator is a common bug:priority_queue<int> highwould give a second max-heap. top()andpop()are separate.pop()returnsvoid. Calltop()first, and never on an empty heap, which is undefined behaviour.- Why
top()is safe here. InaddNum,lowhas just received a number, so it isn't empty. InfindMedian, at least one number has been added, solowis never empty. The even branch also readshigh.top(), and the halves have the same size there, sohighhas at least one value. - Dividing by
2.0. Integer division truncates:(1 + 2) / 2is 1, while(1 + 2) / 2.0is 1.5. The2.0makes the whole division adouble. - The sum can't overflow. Values stay within 100,000 in absolute value, so the sum of two tops fits in an
inteasily. With values near the limits ofint, adding two tops could overflow, and the sum would have to be computed as adoubleorlong long. - The return type.
return low.top();converts aninttodoubleautomatically. A median of 2 comes back as2.0, althoughstd::coutprints a whole-number double as2unless you set its formatting. - Fields. The class has no constructor, so the compiler's default one creates two empty heaps, which is the "holds no numbers yet" state.
Complexity
Let n be the number of values added so far.
addNum: O(log n). It does at most two pushes and two pops, in heaps that together hold n values. Each such operation costs O(log n).
findMedian: O(1). It reads one or two tops and does a single division.
Space: O(n). Every number is stored once, in one of the two heaps.
Edge cases and common mistakes
- A single number. After
addNum(5),lowholds 5 andhighis empty, so the odd branch returns 5 and never toucheshigh.top(). - Duplicates. The stream 5, -3, -3 has the median -3, since both copies are stored. Heaps keep duplicates, and the two heaps simply hold equal values on each side.
- Negative numbers. Nothing in the design depends on the sign. The stream 5, -3, -3, 10 gives medians 5, 1, -3 and 1.
- Asking twice.
findMedianonly reads the tops, so calling it twice returns the same value. - Integer division. Writing
/ 2instead of/ 2.0turns 1.5 into 1 and 3.5 into 3. - Letting the halves drift apart. If the size check is missing,
highcan grow larger thanlowand the tops are no longer the middle values. - Pushing straight into the "right" half. Comparing
numwith the tops and choosing a heap works too, but it needs more cases. Pushing intolow, moving its top tohighand rebalancing handles every case with the same code. - Sorting on every query. It is correct but costs
O(n log n)per call, which is too slow for 500,000 operations.
Testing
- Add 1, 2 and ask: 1.5. Add 3 and ask: 2.
- Add 5 and ask: 5. Add -3 and ask: 1. Add -3 and ask: -3. Add 10 and ask: 1.
- Add 4 and 3, ask twice: 3.5 both times. Add 2 and 1 and ask: 2.5.
- Add 100000 twice and ask: 100000. Add -100000 and ask: 100000.
- Add the numbers 0 to 999, repeated 500 times (500,000 additions), and ask: 499.5.
