Problem overview
The median of a list is its middle value once the list is sorted. With an even number of values, it 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 class MedianFinder receives numbers one at a time through addNum(num), and findMedian() must return the median of everything added so far. It can be asked at any moment, as often as needed, and asking changes nothing. For the calls addNum(1), addNum(2), findMedian(), addNum(3), findMedian() the answers are 1.5 and 2.
Approach
The simple way is to keep an array and sort it before every question, which costs O(n log n) per call. Keeping the array sorted with insertions still moves up to n values each time. The statement asks for addNum in O(log n) and findMedian in O(1).
The median depends only on the middle of the sorted data, so the code splits the numbers into two halves:
- the lower half in a max-heap, whose top is its largest value;
- the upper half in a min-heap, whose top is its smallest value.
Every value in the upper half is at least every value in the lower half, and the halves have the same size or the lower half has one more. Then the middle of the sorted data sits at the two tops: with an odd count the top of the lower half is the median, and with an even count the median is the mean of the two tops. Reading a top is O(1), and inserting into or removing from a heap is O(log n).
The lesson provides ready-to-use MaxHeap and MinHeap classes with insert(value), extract() (removes and returns the top), peek() (reads the top), size() and isEmpty().
Step by step
- The lower half. A field
lowof typeMaxHeap, set tonew MaxHeap(). - The upper half. A field
highof typeMinHeap, set tonew MinHeap(). - Insert into the lower half first. Every new number goes into
this.low, whatever its size. - Move the lower half's largest value up.
this.low.extract()removes and returns it, and it is inserted intothis.high. Whatevernumwas, the value that leaveslowis its largest, so every value inhighstays at least every value inlow. Ifnumwas the largest, it is simply the one that moves. - Rebalance. After step 4,
highmay have one value more thanlow. In that case its smallest value moves back tolow. The halves then differ in size by at most one, withlownever smaller. - Odd count. In
findMedian, iflowholds more values thanhigh, it has exactly one more, so its top is the middle value:this.low.peek(). - Even count. Otherwise the halves are equal, and the median is the mean of the two tops,
(this.low.peek() + this.high.peek()) / 2.
The solution in TypeScript
class MedianFinder {
low: MaxHeap = new MaxHeap();
high: MinHeap = new MinHeap();
addNum(num: number): void {
this.low.insert(num);
this.high.insert(this.low.extract());
if (this.high.size() > this.low.size()) {
this.low.insert(this.high.extract());
}
}
findMedian(): number {
if (this.low.size() > this.high.size()) {
return this.low.peek();
}
return (this.low.peek() + this.high.peek()) / 2;
}
}
Details for TypeScript:
- Field initializers.
low: MaxHeap = new MaxHeap();declares the field and gives it a value when eachMedianFinderis created, so no constructor is needed and every instance gets its own heaps. / 2keeps the fraction. In TypeScript every number is a double, so(1 + 2) / 2is1.5, with no integer division to work around. Because of that, a median that is a whole number comes back as2, not2.0; the number is the same, and only the printed form differs.
Walking through an example
For the numbers 5, -3, -3, 10, each call to addNum leaves the heaps like this:
| Added | Top of low | Top of high | Sizes (low, high) | Median |
|---|---|---|---|---|
| 5 | 5 | none | 1, 0 | 5 |
| -3 | -3 | 5 | 1, 1 | 1 |
| -3 | -3 | 5 | 2, 1 | -3 |
| 10 | -3 | 5 | 2, 2 | 1 |
A number that arrives twice is stored twice, which is why the third row has two values in low and the median is -3.
Complexity
addNum: O(log n). It does at most three heap operations on heaps that hold about n / 2 values each. findMedian: O(1). It reads one or two tops. Space: O(n). Every added number is stored once.
Edge cases and common mistakes
- One number. After
addNum(5),lowholds 5 andhighis empty, so the odd branch returns 5. The even branch is never reached with an emptyhigh, because the problem callsfindMedianonly after at least oneaddNum. - Duplicates. Equal values are separate entries and both count.
- Negative numbers. Nothing in the code depends on the sign.
-3and5give a median of 1. - Asking twice.
findMedianonly reads, so two calls in a row give the same answer. - Skipping the "up, then down" moves. Inserting straight into the right heap needs a comparison with the tops and special cases for empty heaps. Pushing through
lowintohighkeeps the ordering rule without any of that. - Letting the sizes drift. If
highwere allowed to grow larger thanlow, the middle would no longer sit at the tops.
Testing
| Calls | Medians returned |
|---|---|
| add 1, add 2, find, add 3, find | 1.5, 2 |
| add 5, find, add -3, find, add -3, find, add 10, find | 5, 1, -3, 1 |
| add 4, add 3, find, find, add 2, add 1, find | 3.5, 3.5, 2.5 |
