Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in Rust: 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 8
    Ctrl + Enter to check

    RUST · HEAP

    Find Median From Data Stream in Rust, explained

    Problem overview

    The MedianFinder struct receives numbers one at a time and, at any moment, must report the median of everything received so far. The median is the middle value of the sorted numbers. With an even count there are two middle values, and the median is their mean: the median of [2, 3, 4] is 3, and the median of [2, 3] is 2.5.

    The struct has three functions: MedianFinder::new() creates an empty finder, add_num(&mut self, num: i32) adds a number, and find_median(&self) -> f64 returns the median. find_median is only called after at least one number has been added. Adding the numbers 1, 2, 3 and asking after 2 and after 3 numbers gives 1.5 and then 2.0. For 5, -3, -3, 10 the answers after each number are 5.0, 1.0, -3.0, 1.0: a number that arrives twice counts twice.

    Approach: two heaps around the middle

    Sorting all the numbers on every question would cost O(n log n) each time, and keeping a sorted Vec costs O(n) per insertion. The statement asks for O(log n) to add and O(1) to read the median, and two heaps give both.

    Split the numbers into two halves: the smaller half in a max-heap low, whose top is its largest value, and the larger half in a min-heap high, whose top is its smallest. If the halves are kept the same size, or with low one bigger, the middle values always sit on the two tops:

    • With an odd count, low has one more value, and its top is the median.
    • With an even count, the median is the mean of the two tops.

    Pushing and popping a heap cost O(log n) and reading the top costs O(1). Adding a number does a fixed number of pushes and pops, so it stays O(log n), and find_median only reads tops.

    Printing the halves after each number of the sequence 4, 3, 2, 1 shows how they work:

    addedlow (sorted)high (sorted)median
    4[4][]4.0
    3[3][4]3.5
    2[2, 3][4]3.0
    1[1, 2][3, 4]2.5

    The numbers arrive in descending order, yet low always holds the smaller values and high the larger ones.

    Step by step

    1. The lower half. A field low: BinaryHeap<i32>. Rust's BinaryHeap is a max-heap, so its top is the largest value, which is exactly what the lower half needs.
    2. The upper half. A field high: BinaryHeap<Reverse<i32>>. Reverse, from std::cmp, flips the ordering of what it wraps, so this max-heap's top is the smallest number. Reverse(x) wraps x and .0 takes it back out.
    3. new returns a MedianFinder with BinaryHeap::new() for both fields. Rust infers each heap's element type from the field.
    4. Push into the lower half. Every new number goes into low first.
    5. Move the lower half's top to the upper half. self.low.pop().unwrap() removes the largest value of low, and it is pushed into high wrapped in Reverse. Whatever num was, the value that moves is the largest of low, so everything in high stays at least as large as everything in low. unwrap() is safe because num was just pushed.
    6. Rebalance. If high now holds more values than low, pop the smallest value of high, take it out of its Reverse with .0 and push it into low. The halves are then the same size, or low is one bigger.
    7. find_median, odd count. When low has more values, return its top: peek() gives an Option holding a reference, so unwrap it, dereference with *, and convert as f64.
    8. find_median, even count. The halves have the same size, so return the mean of the two tops: the top of low plus .0 of the top of high, converted to f64 and divided by 2.0.

    The solution in Rust

    use std::cmp::Reverse;
    use std::collections::BinaryHeap;
    
    struct MedianFinder {
        low: BinaryHeap<i32>,
        high: BinaryHeap<Reverse<i32>>,
    }
    
    impl MedianFinder {
        fn new() -> MedianFinder {
            MedianFinder { low: BinaryHeap::new(), high: BinaryHeap::new() }
        }
    
        fn add_num(&mut self, num: i32) {
            self.low.push(num);
            self.high.push(Reverse(self.low.pop().unwrap()));
            if self.high.len() > self.low.len() {
                self.low.push(self.high.pop().unwrap().0);
            }
        }
    
        fn find_median(&self) -> f64 {
            if self.low.len() > self.high.len() {
                return *self.low.peek().unwrap() as f64;
            }
            (*self.low.peek().unwrap() + self.high.peek().unwrap().0) as f64 / 2.0
        }
    }
    

    The Rust details worth a closer look:

    • A max-heap used as a min-heap. BinaryHeap has no min-heap mode. Wrapping values in Reverse makes the larger one compare as smaller, so peek() and pop() on high hand back the smallest number. A Reverse<i32> prints as Reverse(1), and its inner number is the field .0.
    • peek() and pop() return an Option. They give None on an empty heap. The code uses unwrap() only where a value is certain to exist: right after a push, and in find_median, which is only called after add_num.
    • &mut self and &self. add_num changes the heaps, so it borrows the struct mutably. find_median only reads, so a shared borrow is enough, and asking twice in a row gives the same answer.
    • Convert before dividing. The sum of two i32 values divided by 2 is integer division: 11 / 2 is 5. Writing as f64 / 2.0 divides as floating-point numbers, so 11 becomes 5.5. The cast applies to the whole parenthesized sum, and then / 2.0 divides.
    • Overflow. The sum is added as i32 before it is converted, which is fine for the values of this lesson, between -100,000 and 100,000. For values near the type's limits the sum wraps in an optimized build: two numbers equal to 2_000_000_000 give -147483648 as their mean, whereas converting each to f64 first gives 2000000000.
    • The return value. The last line has no semicolon, so it is the value returned when the early return doesn't run.

    Complexity

    add_num: O(log n). It does up to two pushes and two pops, and each costs O(log n) in a heap of at most n values.

    find_median: O(1). It reads one or two tops and does a little arithmetic.

    Space: O(n). Every number is stored once, in one of the heaps.

    Edge cases and common mistakes

    • One number. After add_num(5), low holds 5 and high is empty, so find_median returns 5.0 from the odd branch.
    • Duplicates. Both heaps accept equal values. For 5, -3, -3 the median is -3.0, and a second -3 goes into the lower half beside the first.
    • Negative numbers. Nothing special is needed: 5 and -3 give 1.0.
    • Integer division. Dividing the i32 sum by 2 before converting loses the half and turns 3.5 into 3.0.
    • Pushing straight into one half. If a new number went into high or low without the round trip through low, a small number could end up in the upper half and the tops would no longer be the middle values.
    • Letting high grow bigger than low. The odd-count branch relies on low holding the extra value, so the rebalancing step has to keep that rule.
    • Calling find_median first. On an empty finder peek().unwrap() would panic. The lesson guarantees at least one number first.

    Testing

    • Add 1, 2, ask, add 3, ask: 1.5 then 2.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 100000 twice, ask: 100000.0.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free