Problem overview
You implement a class MedianFinder with two methods. AddNum(int num) adds a number to the collection, and FindMedian() returns the median of everything added so far as a double. The median is the middle value of the sorted numbers. With an even count there is no single middle value, so the median is the mean of the two middle ones: the median of [2, 3, 4] is 3, and the median of [2, 3] is 2.5.
The calls come in any order, with at least one AddNum before the first FindMedian. For the calls AddNum(1), AddNum(2), FindMedian(), AddNum(3), FindMedian() the answers are 1.5 and 2.0. Duplicates count: after adding 5, -3 and -3 the sorted numbers are [-3, -3, 5] and the median is -3.
The target is AddNum in O(log n) time and FindMedian in O(1) time, where n is how many numbers have been added.
Approach: two halves, two heaps
The simplest design keeps a list and sorts it for every question, which costs O(n log n) per FindMedian. Keeping the list sorted by inserting each number in its place avoids the sort, but shifting elements in a list still costs O(n) per insertion.
The median only depends on the middle of the sorted order, so you don't need the whole order. Split the numbers into two halves: the lower half and the upper half. Every number in the lower half is at most every number in the upper half. The middle values are then the largest of the lower half and the smallest of the upper half. A max-heap gives instant access to the largest of the lower half, and a min-heap gives instant access to the smallest of the upper half. Reading the top of a heap is O(1), and adding or removing an element is O(log n).
The halves must stay balanced. The lesson keeps the lower half equal in size to the upper half, or one larger. Then:
- with an odd count, the lower half has one extra value, and its top is the median;
- with an even count, the halves have the same size, and the median is the mean of the two tops.
To add a number, push it into the lower half, then move that half's largest value to the upper half. This guarantees that every value in the upper half is at least every value in the lower half, whatever num was. After that the upper half may be one value too big, and if so, its smallest value moves back to the lower half. Each add does a constant number of heap operations.
The run below adds 4, 3, 2, 1, 10 and -5 in turn and prints the two tops and sizes after each add, and the median:
add 4: low top 4 (size 1), high top - (size 0) median 4
add 3: low top 3 (size 1), high top 4 (size 1) median 3.5
add 2: low top 3 (size 2), high top 4 (size 1) median 3
add 1: low top 2 (size 2), high top 3 (size 2) median 2.5
add 10: low top 3 (size 3), high top 4 (size 2) median 3
add -5: low top 2 (size 3), high top 3 (size 3) median 2.5
Step by step
- Declare
low, the lower half, as aPriorityQueue<int, int>built withComparer<int>.Create((x, y) => y - x). C#'sPriorityQueueis a min-heap: it hands out the element with the smallest priority first. The comparer reverses the order, so the largest priority comes out first, which makeslowa max-heap. - Declare
highas a plainPriorityQueue<int, int>. It is a min-heap, the upper half. - In
AddNum, enqueuenumintolow, usingnumas both the element and its priority, so the heap orders the numbers themselves. - Move the largest of
lowintohigh.Dequeuefromlowintolargest, then enqueue it intohigh. Now every value inhighis still at least every value inlow. - Rebalance. If
high.Count > low.Count, the middle values are no longer at the tops. - Move the smallest of
highback tolowthe same way. The halves are now the same size, orlowis one bigger. - In
FindMedian, handle an odd count. Iflowholds more values, returnlow.Peek(), which reads the top without removing it. - Otherwise return the mean of the tops:
(low.Peek() + high.Peek()) / 2.0.
The solution in C#
class MedianFinder {
PriorityQueue<int, int> low = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y - x));
PriorityQueue<int, int> high = new PriorityQueue<int, int>();
public void AddNum(int num) {
low.Enqueue(num, num);
int largest = low.Dequeue();
high.Enqueue(largest, largest);
if (high.Count > low.Count) {
int smallest = high.Dequeue();
low.Enqueue(smallest, smallest);
}
}
public double FindMedian() {
if (low.Count > high.Count) {
return low.Peek();
}
return (low.Peek() + high.Peek()) / 2.0;
}
}
The C# details worth knowing:
PriorityQueue<TElement, TPriority>takes two type arguments. It lives inSystem.Collections.Genericand has existed since .NET 6.Enqueue(element, priority)adds an item,Dequeue()removes and returns the element with the smallest priority, andPeek()returns it without removing it. There is no built-in max-heap, which is whylowreverses the order with a comparer.- The comparer decides what "smallest" means.
Comparer<int>.Create((x, y) => y - x)returns a positive number whenxis smaller thany, so the larger value is treated as having the smaller priority. y - xcan overflow. With the lesson's numbers, which stay within ±100,000, it never does. For arbitraryintvalues the subtraction wraps silently:10 - (int.MinValue + 5)evaluates to -2147483643 instead of a large positive number, so a safer comparer isy.CompareTo(x).- The field initializers run when the object is created. Each
MedianFindergets its own two heaps, so no constructor is needed. - Integer division truncates.
3 / 2is 1 in C#, but3 / 2.0is 1.5, because one operand is adouble. The sum of the two tops is anint, and dividing by2.0keeps the half. - The
intreturn converts todouble.return low.Peek();in a method that returnsdoubleconverts theintimplicitly. An odd count therefore gives 2.0 rather than a whole number type. - Empty heaps throw.
Peek()andDequeue()throwInvalidOperationExceptionwhen the heap is empty. This is whyFindMedianrelies on at least one number having been added.
Complexity
Time. AddNum does at most two Enqueue and two Dequeue calls, each O(log n), so it is O(log n). FindMedian only reads the top of one or two heaps, so it is O(1).
Space: O(n). Every number is stored once, in one of the two heaps.
Edge cases and common mistakes
- A single number. After one
AddNum(7), the number goes tolow, moves tohigh, and moves back, becausehighwould be bigger.FindMedianreturns 7.0. - Even counts. After 4 and 3 the median is 3.5, the mean of the two tops.
- Duplicates. Repeated values count each time. Adding 5, -3, -3 gives the median -3.0.
- Negative numbers. They need no special handling: 5, -3 gives 1.0.
- Asking twice.
FindMedianonly peeks, so calling it twice in a row returns the same value. - Dividing by
2instead of2.0. The code would return 1 for the tops 1 and 2, instead of 1.5. - Letting the halves drift apart. If
highis allowed to grow larger thanlow, or the sizes differ by more than one, the tops are no longer the middle values. - Skipping the pass through
low. Pushing a number straight into the half it seems to belong to needs a comparison against the tops. Always pushing intolowand moving its largest value over makes that check unnecessary.
Testing
These call sequences were run, and FindMedian printed the values shown.
- Add 1, 2, ask, add 3, ask gives
1.5 2.0. - Add 5, ask, add -3, ask, add -3, ask, add 10, ask gives
5.0 1.0 -3.0 1.0. - Add 4, 3, ask, ask, add 2, 1, ask gives
3.5 3.5 2.5. - Add 7, ask gives
7.0. - 20,000 random numbers between -100,000 and 100,000, checked against sorting the list every so often, give identical medians.
