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 class MedianFinder receives numbers one at a time through addNum(num), and findMedian() returns the median of everything added so far, as a Double.
After adding 1 and 2, the median is 1.5. After adding 3 the sorted numbers are [1, 2, 3] and the median is 2.0. A number that arrives twice counts twice, so after 5, -3 and -3 the median is -3.0.
The statement asks for addNum in O(log n) time and findMedian in O(1).
Approach
Keeping a sorted list makes findMedian trivial but addNum slow, because inserting in the middle shifts elements. Sorting all the numbers at every question costs O(n log n) each time. The fast idea uses the fact that only the middle of the sorted data matters.
Split the numbers into two halves: the smaller half and the larger half. Keep the smaller half in a max-heap, whose top is its largest value, and the larger half in a min-heap, whose top is its smallest value. Then the two middle values are always the two tops, and reading a top is O(1). Adding a number is a few heap pushes and pops, each O(log n).
The halves are kept balanced: they have the same size, or the lower half has exactly one more value. With an odd count the median is the top of the lower half. With an even count it is the mean of the two tops.
Step by step
- Declare
low, the lower half, aPriorityQueue<Int>created withcompareByDescending { it }. Kotlin'sPriorityQueueis a min-heap by default, and this comparator reverses the order so the largest value is on top. - Declare
high, the upper half, as a plainPriorityQueue<Int>(), a min-heap. - In
addNum, addnumtolowfirst. Every new number enters the lower half, and the next lines restore the order. - Move the largest value of
lowintohigh.low.poll()removes and returns it. Whatevernumwas, the value that leaves is the largest of the lower half, so every value inhighstays at least as large as every value inlow. - Rebalance. If
highnow holds more values thanlow, move the smallest value ofhighback intolow. Afterwards the sizes are equal, orlowhas one more. - In
findMedian, handle the odd case. Iflowholds more values thanhigh, its top,low.peek(), is the middle value.peek()reads the top without removing it. Kotlin never converts anIntto aDoubleon its own, so the code callstoDouble(). - Handle the even case. Both halves have the same size, so return the sum of the two tops divided by
2.0.
The solution in Kotlin
class MedianFinder {
val low = PriorityQueue<Int>(compareByDescending { it })
val high = PriorityQueue<Int>()
fun addNum(num: Int) {
low.add(num)
high.add(low.poll())
if (high.size > low.size) {
low.add(high.poll())
}
}
fun findMedian(): Double {
if (low.size > high.size) {
return low.peek().toDouble()
}
return (low.peek() + high.peek()) / 2.0
}
}
Some Kotlin details in this code:
PriorityQueueis a Java class fromjava.util, which Kotlin on the JVM can use directly. In a file of your own you needimport java.util.PriorityQueueat the top.compareByDescending { it }builds a comparator that orders integers from largest to smallest. Without it the queue puts the smallest value on top.low.poll()returns a platform type, so Kotlin does not force a null check on it. It is safe here becauselowalways holds at least the number just added, andhighis polled only when it has more values thanlow.(low.peek() + high.peek()) / 2.0adds twoIntvalues first. Dividing anIntby2.0gives aDoubleand keeps the half:3 / 2is1, but3 / 2.0is1.5. The numbers here are at most 100,000 in size, so the sum cannot overflow.Intaddition wraps silently, though:2000000000 + 2000000000held in variables gives-294967296, so with larger values you would add asLongorDouble.
Following the second example
Adding 5, -3, -3 and 10, with the two halves and the median after each call:
add 5: low=[5] high=[] median=5.0
add -3: low=[-3] high=[5] median=1.0
add -3: low=[-3, -3] high=[5] median=-3.0
add 10: low=[-3, -3] high=[5, 10] median=1.0
After the second call, -3 is the single value of the lower half and 5 of the upper half, so the median is (-3 + 5) / 2.0 = 1.0. After the third call the lower half has an extra value, so the median is its top, -3.0.
Complexity
addNum: O(log n). It does at most three pushes and two pops on heaps of size about n / 2, and each costs O(log n).
findMedian: O(1). It only reads the tops of the heaps and does one division.
Space: O(n). Every number is stored once, in one of the two heaps.
Edge cases and common mistakes
- One number. After
addNum(5),lowholds 5 andhighis empty, sofindMedian()returns5.0. The code readshigh.peek()only when both heaps have the same size, which means both are non-empty. - Calling
findMediantwice. It changes nothing, so it returns the same value both times. - Unsorted input. After 4, 3, 2 and 1 the median is 2.5, whatever the order the numbers arrive in.
- Integer division. Writing
/ 2instead of/ 2.0drops the half, so(2 + 3) / 2would give2instead of2.5. - Wrong heap direction. If
lowwere a plain min-heap, its top would be its smallest value, not the middle one.
Testing
addNum(1) addNum(2) findMedian() addNum(3) findMedian() -> 1.5 2.0
addNum(4) addNum(3) findMedian() findMedian() addNum(2) addNum(1) findMedian() -> 3.5 3.5 2.5
addNum(100000) addNum(99999) findMedian() -> 99999.5
