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,
lowhas 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:
| added | low (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
- The lower half. A field
low: BinaryHeap<i32>. Rust'sBinaryHeapis a max-heap, so its top is the largest value, which is exactly what the lower half needs. - The upper half. A field
high: BinaryHeap<Reverse<i32>>.Reverse, fromstd::cmp, flips the ordering of what it wraps, so this max-heap's top is the smallest number.Reverse(x)wrapsxand.0takes it back out. newreturns aMedianFinderwithBinaryHeap::new()for both fields. Rust infers each heap's element type from the field.- Push into the lower half. Every new number goes into
lowfirst. - Move the lower half's top to the upper half.
self.low.pop().unwrap()removes the largest value oflow, and it is pushed intohighwrapped inReverse. Whatevernumwas, the value that moves is the largest oflow, so everything inhighstays at least as large as everything inlow.unwrap()is safe becausenumwas just pushed. - Rebalance. If
highnow holds more values thanlow, pop the smallest value ofhigh, take it out of itsReversewith.0and push it intolow. The halves are then the same size, orlowis one bigger. find_median, odd count. Whenlowhas more values, return its top:peek()gives anOptionholding a reference, so unwrap it, dereference with*, and convertas f64.find_median, even count. The halves have the same size, so return the mean of the two tops: the top oflowplus.0of the top ofhigh, converted tof64and divided by2.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.
BinaryHeaphas no min-heap mode. Wrapping values inReversemakes the larger one compare as smaller, sopeek()andpop()onhighhand back the smallest number. AReverse<i32>prints asReverse(1), and its inner number is the field.0. peek()andpop()return anOption. They giveNoneon an empty heap. The code usesunwrap()only where a value is certain to exist: right after a push, and infind_median, which is only called afteradd_num.&mut selfand&self.add_numchanges the heaps, so it borrows the struct mutably.find_medianonly reads, so a shared borrow is enough, and asking twice in a row gives the same answer.- Convert before dividing. The sum of two
i32values divided by2is integer division:11 / 2is5. Writingas f64 / 2.0divides as floating-point numbers, so11becomes5.5. The cast applies to the whole parenthesized sum, and then/ 2.0divides. - Overflow. The sum is added as
i32before 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 to2_000_000_000give-147483648as their mean, whereas converting each tof64first gives2000000000. - The return value. The last line has no semicolon, so it is the value returned when the early
returndoesn'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),lowholds 5 andhighis empty, sofind_medianreturns5.0from the odd branch. - Duplicates. Both heaps accept equal values. For 5, -3, -3 the median is
-3.0, and a second-3goes into the lower half beside the first. - Negative numbers. Nothing special is needed: 5 and -3 give
1.0. - Integer division. Dividing the
i32sum by 2 before converting loses the half and turns3.5into3.0. - Pushing straight into one half. If a new number went into
highorlowwithout the round trip throughlow, a small number could end up in the upper half and the tops would no longer be the middle values. - Letting
highgrow bigger thanlow. The odd-count branch relies onlowholding the extra value, so the rebalancing step has to keep that rule. - Calling
find_medianfirst. On an empty finderpeek().unwrap()would panic. The lesson guarantees at least one number first.
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 100000 twice, ask:
100000.0.
