Problem overview
The median of a list of numbers is the middle value once the list is sorted. With an even number of values there is no single middle, so the median is the mean of the two middle values: the median of [2, 3, 4] is 3 and the median of [2, 3] is 2.5.
The lesson asks for a class MedianFinder with two methods. addNum(num) takes an Int and stores it. findMedian() returns the median of every number added so far, as a Double. It is only called after at least one number has been added.
In the first example, after adding 1 and 2 the median is 1.5, and after adding 3 as well it is 2.0. In the second, adding 5, -3, -3 and 10 gives the medians 5.0, 1.0, -3.0 and 1.0: a number that arrives twice counts twice. The statement asks for addNum in O(log n) time and findMedian in O(1).
Approach: the middle sits at the top of two heaps
The simple idea keeps a list and sorts it whenever the median is requested. That costs O(n log n) per question. Inserting into an already sorted array avoids the sort, but shifting elements makes each insertion O(n).
The lesson takes a different route. The median depends only on the values around the middle, so it splits the numbers into two halves:
lowholds the smaller half in a max-heap, whose top is its largest value;highholds the larger half in a min-heap, whose top is its smallest value.
Every value in high is at least every value in low, so the two middle values of the whole collection are always the two tops. The halves are kept the same size, or with low exactly one larger. Then an odd count has its middle value on top of low, and an even count has its two middle values on top of the two heaps.
Adding a number needs two heap moves to keep both rules true. The new number goes into low first. Then the largest value of low moves to high, which guarantees that nothing in high is smaller than anything in low, whatever the new number was. If that left high with more values than low, the smallest value of high moves back. Each heap operation costs O(log n), and reading a top is O(1).
Here is the state after adding 5, -3, -3 and 10 in turn, with the tops of both heaps:
| added | top of low | size of low | top of high | size of high | median |
|---|---|---|---|---|---|
| 5 | 5 | 1 | none | 0 | 5.0 |
| -3 | -3 | 1 | 5 | 1 | 1.0 |
| -3 | -3 | 2 | 5 | 1 | -3.0 |
| 10 | -3 | 2 | 5 | 2 | 1.0 |
Step by step
- Declare
low.PriorityQueue[Int]()in aval. Scala's mutablePriorityQueueis a max-heap by default, which is what the lower half needs. - Declare
high. The same type with a second pair of parentheses holdingOrdering[Int].reverse. Reversing the ordering makes the smallest number count as the largest, so the smallest sits on top. - In
addNum, enqueue the number intolow. Every new number enters the lower half first. - Move the top of
lowtohigh.low.dequeue()removes and returns the largest value inlow, andhigh.enqueue(...)receives it in the same line. - Rebalance. If
high.sizeexceedslow.size, the smallest value ofhighgoes back intolow. After this step the sizes are equal, orlowhas one more. - In
findMedian, handle the odd case. Whenlowholds more values thanhigh, the count is odd andlow.head, the top oflow, is the median.headreads the top without removing it, andtoDoublemakes the return type fit. - Handle the even case. The sizes are equal, so the median is the sum of the two tops divided by
2.0.
The solution in Scala
class MedianFinder {
val low = PriorityQueue[Int]()
val high = PriorityQueue[Int]()(Ordering[Int].reverse)
def addNum(num: Int): Unit = {
low.enqueue(num)
high.enqueue(low.dequeue())
if (high.size > low.size) {
low.enqueue(high.dequeue())
}
}
def findMedian(): Double = {
if (low.size > high.size) {
return low.head.toDouble
}
return (low.head + high.head) / 2.0
}
}
The lesson's file already imports scala.collection.mutable.PriorityQueue; in a program of your own, add that import. The Scala details worth a closer look:
- Max-heap by default.
PriorityQueue[Int]()uses the natural ordering ofIntand puts the largest element athead. Forenqueue(3, 9, 1)the head is 9. The reversed queue holds the same values with 1 at its head. - The second parameter list. The constructor takes its
Orderingin a separate parameter list, which is why the code readsPriorityQueue[Int]()(Ordering[Int].reverse). The first()holds the optional initial elements, and the second holds the ordering. headis notdequeue().headonly reads the top.dequeue()removes it. The problem guarantees thatfindMediancomes after at least oneaddNum, so there is always a top to read.- Integer division versus
2.0.3 / 2is theInt1, but3 / 2.0is theDouble1.5. Dividing the sum by2.0keeps the half. - Int addition happens first.
low.head + high.headis anIntsum, and only the division is done inDouble. With values in the problem's range of plus or minus 100,000 the sum cannot overflow. WithIntvalues near the limit it would wrap: two copies of 2000000000 give-1.47483648E8. - Printing.
println(2.0)prints2.0in Scala, which matches the one-digit format the lesson's output uses.
Complexity
Time. addNum performs three heap operations (an enqueue, a dequeue and an enqueue), plus one more dequeue and enqueue when it rebalances: at most five in all. Each costs O(log n), so addNum is O(log n). findMedian reads one or two tops and does one division, so it is O(1).
Space: O(n). Every number added is stored in exactly one of the two heaps.
Edge cases and common mistakes
- One number. After
addNum(5)the number moves fromlowtohighand straight back, solowholds it and the median is 5.0. - Duplicates. Adding -3 twice stores two copies, and the median counts both: after 5, -3, -3 it is -3.0.
- Calling
findMediantwice. It changes nothing, so asking twice gives the same answer: after adding 4 and 3, both calls return 3.5. - Numbers out of order. Adding 4, 3, 2, 1 gives 3.5 after the first two numbers and 2.5 after all four. The heaps do not care about the arrival order.
- Letting the sizes drift. If
lowwere allowed to grow two values bigger thanhigh, the middle values would no longer sit at the tops. The rebalancing step prevents that. - Using the same ordering for both heaps. Two max-heaps would put the largest values on top of both, and
high.headwould not be the smallest of the upper half. - Integer division. Writing
/ 2instead of/ 2.0would turn 1.5 into 1.
Testing
addNum(1),addNum(2),findMedian()gives1.5. AfteraddNum(3),findMedian()gives2.0.- Adding 5, -3, -3, 10, with
findMedian()after each, gives5.0,1.0,-3.0,1.0. - Adding 4 and 3 gives
3.5, twice in a row. Then adding 2 and 1 gives2.5.
