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 task is to implement a class MedianFinder. Numbers arrive one at a time through addNum(num), and findMedian() returns the median of everything added so far. A number that arrives twice counts twice, and findMedian is only called after at least one number has been added.
For example, after addNum(5), addNum(-3), addNum(-3) and addNum(10), the successive medians are 5, 1, -3 and 1. The statement asks for O(log n) time for addNum and O(1) time for findMedian.
Approach: two halves, two heaps
The simple solution keeps an array and sorts it for every question. That costs O(n log n) per findMedian, which is too slow with up to 500,000 calls. Keeping the array sorted as numbers arrive doesn't help much either, because inserting into the middle of an array shifts many elements.
The median only depends on the middle one or two values, so the lesson keeps just enough order to find them. It splits the numbers into two halves:
low, a max-heap holding the smaller half. Its top is the largest value of that half.high, a min-heap holding the larger half. Its top is the smallest value of that half.
Every value in high is at least every value in low, so the two middle values of the whole list are the two tops. The halves are kept balanced: the same size, or low one bigger. Then:
- With an odd count,
lowholds one extra value, and its top is the median. - With an even count, the median is the mean of the two tops.
Pushing to or popping from a heap costs O(log n), and reading the top costs O(1), which gives the budget the statement sets.
Here is how the halves change as 5, 15, 1 and 3 arrive:
| added | size of low | top of low | size of high | top of high | findMedian() |
|---|---|---|---|---|---|
| 5 | 1 | 5 | 0 | none | 5 |
| 15 | 1 | 5 | 1 | 15 | 10 |
| 1 | 2 | 5 | 1 | 15 | 5 |
| 3 | 2 | 3 | 2 | 5 | 4 |
Step by step
- Create
this.lowin the constructor as aMaxHeapfrom thealgorithmslibrary. JavaScript has no built-in heap, so the lesson uses this one. The lesson providesinsert(value),extract(),peek()and the sizenon its heaps. - Create
this.highas aMinHeapfrom the same place. - In
addNum, insertnumintothis.lowfirst. Every new number starts in the lower half, and the next lines restore the order. - Move the largest value of
this.lowintothis.high:extract()removes and returns it, andinsertputs it in the other heap. Whatevernumwas, the value that leaves the lower half is its largest, so everything inhighstays at least everything inlow. - Rebalance. If
highnow has more values thanlow, move the smallest value ofhighback intolow. The halves are then the same size, orlowis one bigger. - In
findMedian, handle an odd count. Iflowhas more values thanhigh, its top,peek(), is the middle value. - Otherwise the halves are equal, and the median is the sum of the two tops divided by 2.
The solution in JavaScript
var algorithms = require('algorithms')
class MedianFinder {
constructor() {
this.low = new algorithms.DataStructures.Heap.MaxHeap();
this.high = new algorithms.DataStructures.Heap.MinHeap();
}
addNum(num) {
this.low.insert(num);
this.high.insert(this.low.extract());
if (this.high.n > this.low.n) {
this.low.insert(this.high.extract());
}
}
findMedian() {
if (this.low.n > this.high.n) {
return this.low.peek();
}
return (this.low.peek() + this.high.peek()) / 2;
}
}
The JavaScript details worth a closer look:
require('algorithms'). This loads the heap library as a Node module. The heaps live underalgorithms.DataStructures.Heap.- Fields on
this.this.lowandthis.highbelong to eachMedianFinderinstance, so two finders never share data. nis a property, not a method. It is writtenthis.low.n, without parentheses./keeps the fraction. In JavaScript every number is a double, so7 / 2is3.5and no conversion is needed. There is no separate integer type to cast to.- Whole medians are plain numbers.
findMedianreturns the number2, not2.0: JavaScript prints both the same way. Formatting with a decimal digit is a matter of how the result is displayed.
The two-step insert looks roundabout, but it makes the code short and correct for every case. Inserting into low and then moving its top to high guarantees the order between the halves, and the single rebalance step guarantees the sizes. There are no cases to compare against the tops.
Complexity
addNum: O(log n). It does at most two inserts and two extracts, each O(log n) in a heap of up to n values.
findMedian: O(1). It reads one or two tops and does one addition and one division.
Space: O(n). Every number added is stored in one of the two heaps.
Edge cases and common mistakes
- A single number. After
addNum(7),lowholds 7 andhighis empty, and the median is 7. The odd branch returns beforehigh.peek()is needed. - Duplicates.
5, -3, -3gives -3. Every copy is stored in a heap, so repeated numbers count each time. - Numbers out of order. Adding 4, 3, 2, 1 gives medians 4, 3.5, 3 and 2.5. The heaps handle any order.
- Asking twice.
findMedianonly reads the tops, so repeating it gives the same answer. - Wrong sizes. If
highwere allowed to grow bigger thanlow, the odd branch would return the wrong half's top. The rebalance step prevents it. - Heaps the wrong way round. The lower half must be a max-heap and the upper half a min-heap. Swapping them puts the extremes of the whole list at the tops instead of the middle values.
- Forgetting that the mean can be a fraction. The median of
[1, 2]is 1.5, so the even branch must divide with/and not floor the result.
Testing
Medians returned by findMedian for these sequences of calls:
addNum(1),addNum(2),findMedian(),addNum(3),findMedian()gives 1.5 and then 2.addNum(5),findMedian(),addNum(-3),findMedian(),addNum(-3),findMedian(),addNum(10),findMedian()gives 5, 1, -3 and 1.addNum(4),addNum(3),findMedian(),findMedian(),addNum(2),addNum(1),findMedian()gives 3.5, 3.5 and 2.5.addNum(7),findMedian()gives 7.
