Problem overview
The median of a list is its middle value once the list is sorted. With an even number of values there are two middle ones, and the median is their mean: the median of [2, 3, 4] is 3, and the median of [2, 3] is 2.5.
The task is a type, MedianFinder, that receives integers one at a time and can be asked for the median of everything received so far. It has a Constructor that returns an empty finder, a method AddNum(num int) and a method FindMedian() float64. FindMedian is only called after at least one number was added, and up to 500,000 calls are made in total.
Adding 5, -3, -3 and then 10, with a question after each number, gives medians 5.0, 1.0, -3.0 and 1.0. A number that arrives twice counts twice. The expected costs are O(log n) for AddNum and O(1) for FindMedian.
Approach: two heaps around the middle
The simplest design keeps every number in a slice and sorts it on every question. That costs O(n log n) per question, which is too slow for this many calls. Inserting each new number into its place in a sorted slice makes the question cheap but shifts elements on every insertion.
The median only depends on the values in the middle, so there is no need to keep everything sorted. Split 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, so the middle of the sorted data sits at the two tops. Keep the halves the same size, or the lower half one bigger. Then, for an odd count, the median is the top of the lower half. For an even count, it is the mean of the two tops. A heap gives its top in O(1) and takes a push or a pop in O(log n), which matches the targets.
The lesson provides the two heap types, maxHeap and minHeap. Both implement heap.Interface from the standard container/heap package, and index 0 of each holds its top.
Step by step
- Add the lower half. The struct gets a field
lowof typemaxHeap. ItsLessis reversed, so the heap package keeps the largest value at index 0. - Add the upper half. A field
highof typeminHeapkeeps the smallest value at index 0. - Write the constructor. It returns
MedianFinder{}. Both fields start as empty (nil) slices, andappendworks on those, so no setup is needed. - Push the new number into
lowwithheap.Push(&this.low, num). The pointer is needed because pushing grows the slice. - Move the largest of
lowintohigh.heap.Pop(&this.low)removes the top oflow, and its result goes straight intoheap.Push(&this.high, ...). Whatevernumwas, the value leavinglowis its largest, so everything inhighstays at least as large as everything inlow. - Rebalance. The previous step may have left
highbigger. Ifthis.high.Len() > this.low.Len(), move the smallest value ofhighback intolow. - Odd count. In
FindMedian, whenlowholds more values thanhigh, the top oflowis the middle, and it is converted tofloat64. - Even count. Otherwise both halves have the same size. Convert the sum of the two tops to
float64and divide by 2.
The solution in Go
type MedianFinder struct {
low maxHeap
high minHeap
}
func Constructor() MedianFinder {
return MedianFinder{}
}
func (this *MedianFinder) AddNum(num int) {
heap.Push(&this.low, num)
heap.Push(&this.high, heap.Pop(&this.low))
if this.high.Len() > this.low.Len() {
heap.Push(&this.low, heap.Pop(&this.high))
}
}
func (this *MedianFinder) FindMedian() float64 {
if this.low.Len() > this.high.Len() {
return float64(this.low[0])
}
return float64(this.low[0] + this.high[0]) / 2
}
Here is the state after each number of the sequence 5, -3, -3, 10, with the two tops and sizes of the halves:
| Added | low top (size) | high top (size) | Median |
|---|---|---|---|
| 5 | 5 (1) | empty (0) | 5.0 |
| -3 | -3 (1) | 5 (1) | 1.0 |
| -3 | -3 (2) | 5 (1) | -3.0 |
| 10 | -3 (2) | 5 (2) | 1.0 |
Look at the second row. The number -3 goes into low next to 5, then 5, the largest, moves to high. The halves are balanced, with sizes 1 and 1. On the third row, the second -3 goes into low, and its largest value, -3, moves to high, which would make high bigger, so the smallest of high, -3, goes back. The net effect is that low gains the number and high is unchanged.
The same finder, given 4, 3, 2, 1 with a question after each number, answers 4.0, 3.5, 3.0 and 2.5.
Go details
heap.Pushandheap.Poptake a pointer. They call thePushandPopmethods ofheap.Interface, which have pointer receivers because they change the slice's length. That is why the code writes&this.low. A plainthis.lowwould not compile, becausemaxHeapitself doesn't have those methods.anyin,anyout.heap.Pushtakes its value asany, andheap.Popreturnsany. Passing one's result straight into the other works without a type assertion, and passing theintnumtoheap.Pushneeds no conversion.- Reading the top is plain indexing. A heap is a slice underneath, and the heap package keeps the best value at index 0, so
this.low[0]reads the top without removing it. - Convert before dividing. Go never converts between number types on its own, and integer division drops the fraction. With the two tops 2 and 3,
(2 + 3) / 2on integers gives2, whilefloat64(2 + 3) / 2gives2.5. In the solution,float64(this.low[0] + this.high[0]) / 2converts the sum first, so the division is a float division. - The zero value is usable.
MedianFinder{}has two nil slices, which are valid empty heaps. The pointer receiver onAddNummeans calls on an addressable variable such asm := Constructor()changemitself.
Complexity
AddNum: O(log n). It does at most three pushes and two pops, each O(log n) in the size of the heap.
FindMedian: O(1). It reads one or two array positions and does an addition and a division.
Space: O(n). Every number is stored once, in one of the two heaps.
Edge cases and common mistakes
- One number. After
AddNum(7), the number moves tohighand straight back tolow, solowholds it and the median is7. The even-count branch is never reached with an emptyhigh. - Duplicates. Equal values are stored separately and counted separately, so 5, -3, -3 gives a median of
-3.0. - Extreme values. Adding 7, -100000 and 100000 gives a median of
7. The sum of two tops is at most 200,000 in size, which is no problem forint. - Asking twice.
FindMediandoesn't change anything, so two calls in a row return the same value. - Dividing integers. Writing
float64(this.low[0] + this.high[0] / 2)puts the parenthesis in the wrong place. The division then happens on integers, and for the tops 2 and 3 the result is3.0instead of2.5. - Passing the heap by value.
heap.Push(this.low, num)doesn't compile. Without a pointer, the slice would be a copy and the caller's heap would not grow. - Forgetting to rebalance. Without the last
if,highwould grow faster thanlowand the tops would no longer be the middle values. - Sorting on every question. It gives correct answers but is
O(n log n)each time, which is too slow for 500,000 calls.
Testing
- Add 1, 2, ask, add 3, ask:
1.5then2.0. - Add 5, ask, add -3, ask, add -3, ask, add 10, ask:
5.0,1.0,-3.0,1.0. - Add 4, 3, ask twice, add 2, 1, ask:
3.5,3.5,2.5. - Add 7, ask:
7.0.
