Start learning free

LESSON 177 OF 314 · HEAP

Find Median From Data Stream in Kotlin: Two Heaps, O(log n) Insert

Practice O(log n) Read the full explanation

The median of a list of numbers is the middle value once the list is sorted. When the list has an even number of values, there is no single middle value, and the median is the mean of the two middle values:

  • the median of [2, 3, 4] is 3;
  • the median of [2, 3] is (2 + 3) / 2 = 2.5.

Numbers arrive one at a time, and at any moment you may be asked for the median of all the numbers that have arrived so far. Implement the class MedianFinder:

  • MedianFinder() creates an object that holds no numbers yet.
  • addNum(num) adds the integer num to the numbers seen so far.
  • findMedian() returns the median of all the numbers added so far.

The input is a list of operations, applied in order to one new MedianFinder. The output lists what the findMedian calls return, in order, each printed with one digit after the decimal point (2.0, 2.5). The starter code spells these names the way your language does.

 

Example 1:

Input:
    addNum(1)
    addNum(2)
    findMedian()
    addNum(3)
    findMedian()
Output: 1.5 2.0
Explanation:
After 1 and 2, there are two middle values, so the median is (1 + 2) / 2 = 1.5.
After 3 arrives, the sorted numbers are [1, 2, 3], and the middle one is 2.

Example 2:

Input:
    addNum(5)
    findMedian()
    addNum(-3)
    findMedian()
    addNum(-3)
    findMedian()
    addNum(10)
    findMedian()
Output: 5.0 1.0 -3.0 1.0
Explanation:
[5] has the median 5. [-3, 5] has the median (-3 + 5) / 2 = 1.
[-3, -3, 5] has the median -3: a number that arrives twice counts twice.
[-3, -3, 5, 10] has the median (-3 + 5) / 2 = 1.

Example 3:

Input:
    addNum(4)
    addNum(3)
    findMedian()
    findMedian()
    addNum(2)
    addNum(1)
    findMedian()
Output: 3.5 3.5 2.5
Explanation: The numbers don't arrive in sorted order, and asking twice in a row gives the same answer, because findMedian changes nothing. At the end the sorted numbers are [1, 2, 3, 4], so the median is (2 + 3) / 2 = 2.5.

 

Constraints:

  • -105 <= num <= 105
  • findMedian is called only after at least one call to addNum.
  • At most 5 * 105 calls in total are made to addNum and findMedian.

Note:

addNum should run in O(log n) time and findMedian in O(1) time, where n is the number of values added so far.

STEP 1 OF 7
    Ctrl + Enter to check

    KOTLIN · HEAP

    Find Median From Data Stream in Kotlin, explained

    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

    1. Declare low, the lower half, a PriorityQueue<Int> created with compareByDescending { it }. Kotlin's PriorityQueue is a min-heap by default, and this comparator reverses the order so the largest value is on top.
    2. Declare high, the upper half, as a plain PriorityQueue<Int>(), a min-heap.
    3. In addNum, add num to low first. Every new number enters the lower half, and the next lines restore the order.
    4. Move the largest value of low into high. low.poll() removes and returns it. Whatever num was, the value that leaves is the largest of the lower half, so every value in high stays at least as large as every value in low.
    5. Rebalance. If high now holds more values than low, move the smallest value of high back into low. Afterwards the sizes are equal, or low has one more.
    6. In findMedian, handle the odd case. If low holds more values than high, its top, low.peek(), is the middle value. peek() reads the top without removing it. Kotlin never converts an Int to a Double on its own, so the code calls toDouble().
    7. 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:

    • PriorityQueue is a Java class from java.util, which Kotlin on the JVM can use directly. In a file of your own you need import java.util.PriorityQueue at 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 because low always holds at least the number just added, and high is polled only when it has more values than low.
    • (low.peek() + high.peek()) / 2.0 adds two Int values first. Dividing an Int by 2.0 gives a Double and keeps the half: 3 / 2 is 1, but 3 / 2.0 is 1.5. The numbers here are at most 100,000 in size, so the sum cannot overflow. Int addition wraps silently, though: 2000000000 + 2000000000 held in variables gives -294967296, so with larger values you would add as Long or Double.

    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), low holds 5 and high is empty, so findMedian() returns 5.0. The code reads high.peek() only when both heaps have the same size, which means both are non-empty.
    • Calling findMedian twice. 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 / 2 instead of / 2.0 drops the half, so (2 + 3) / 2 would give 2 instead of 2.5.
    • Wrong heap direction. If low were 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
    
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free