#295
Hard Algorithms Find median from data stream
Two Pointers Design Sorting Heap (Priority Queue) Data Stream
54.2% acceptance
Jan 12, 2026
13127
283
The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value, and the median is the mean of the two middle values.
For example, for arr = [2,3,4], the median is 3.
For example, for arr = [2,3], the median is (2 + 3) / 2 = 2.5.
Implement the MedianFinder class:
MedianFinder() initializes the MedianFinder object.
void addNum(int num) adds the integer num from the data stream to the data structure.
double findMedian() returns the median of all elements so far. Answers within 10-5 of the actual answer will be accepted.
Solution
Rust
Time O(2^n)
Space O(n)
* impl MedianFinder {
* fn new() -> Self {
* }
* fn add_num(&self, num: i32) {
* }
* fn find_median(&self) -> f64 {
* }
* }
*/
struct MedianFinder {
max_heap: std::cell::RefCell<std::collections::BinaryHeap<i32>>,
min_heap: std::cell::RefCell<std::collections::BinaryHeap<std::cmp::Reverse<i32>>>,
}
impl MedianFinder {
fn new() -> Self {
MedianFinder {
max_heap: std::cell::RefCell::new(std::collections::BinaryHeap::new()),
min_heap: std::cell::RefCell::new(std::collections::BinaryHeap::new()),
}
}
fn add_num(&self, num: i32) {
let mut max_heap = self.max_heap.borrow_mut();
let mut min_heap = self.min_heap.borrow_mut();
if max_heap.is_empty() || num <= *max_heap.peek().unwrap() {
max_heap.push(num);
} else {
min_heap.push(std::cmp::Reverse(num));
}
if max_heap.len() > min_heap.len() + 1 {
let val = max_heap.pop().unwrap();
min_heap.push(std::cmp::Reverse(val));
} else if min_heap.len() > max_heap.len() {
let std::cmp::Reverse(val) = min_heap.pop().unwrap();
max_heap.push(val);
}
}
fn find_median(&self) -> f64 {
let max_heap = self.max_heap.borrow();
let min_heap = self.min_heap.borrow();
if max_heap.len() > min_heap.len() {
*max_heap.peek().unwrap() as f64
} else {
(*max_heap.peek().unwrap() + min_heap.peek().unwrap().0) as f64 / 2.0
}
}
}
/*
* Your MedianFinder object will be instantiated and called as such:
* let obj = MedianFinder::new();
* obj.add_num(num);
* let ret_2: f64 = obj.find_median();
*/