Bird
Raised Fist0
DSA Rustprogramming~20 mins

Median of Data Stream Using Two Heaps in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Median Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the median after inserting these numbers?
Consider a data stream where numbers are inserted one by one. Using two heaps (a max-heap for the lower half and a min-heap for the upper half), what is the median after inserting the sequence: 5, 15, 1, 3?
DSA Rust
use std::collections::BinaryHeap;

fn main() {
    let mut max_heap = BinaryHeap::new(); // lower half
    let mut min_heap = BinaryHeap::new(); // upper half (store negative values to simulate min-heap)

    let nums = vec![5, 15, 1, 3];

    for &num in &nums {
        if max_heap.peek().map_or(true, |&x| num <= x) {
            max_heap.push(num);
        } else {
            min_heap.push(-num);
        }

        // Balance heaps
        if max_heap.len() > min_heap.len() + 1 {
            if let Some(top) = max_heap.pop() {
                min_heap.push(-top);
            }
        } else if min_heap.len() > max_heap.len() {
            if let Some(top) = min_heap.pop() {
                max_heap.push(-top);
            }
        }
    }

    // Calculate median
    let median = if max_heap.len() == min_heap.len() {
        (*max_heap.peek().unwrap() + (-*min_heap.peek().unwrap())) as f64 / 2.0
    } else {
        *max_heap.peek().unwrap() as f64
    };

    println!("Median: {:.1}", median);
}
AMedian: 3.0
BMedian: 6.0
CMedian: 5.0
DMedian: 4.0
Attempts:
2 left
💡 Hint
Balance the heaps after each insertion and then find the middle value(s).
🧠 Conceptual
intermediate
1:30remaining
Why use two heaps to find the median in a data stream?
Which of the following best explains why two heaps (a max-heap and a min-heap) are used to find the median efficiently in a data stream?
ATwo heaps allow splitting the data into lower and upper halves, making median retrieval O(1) after balancing.
BTwo heaps store all data sorted, so median is the middle element in one heap.
CTwo heaps reduce memory usage by storing only half the data each.
DTwo heaps allow parallel insertion of data to speed up processing.
Attempts:
2 left
💡 Hint
Think about how median relates to the middle values of sorted data.
🔧 Debug
advanced
2:00remaining
Identify the bug in this median finder implementation
What error will this Rust code cause when inserting numbers into the two heaps for median calculation?
DSA Rust
use std::collections::BinaryHeap;

fn main() {
    let mut max_heap = BinaryHeap::new();
    let mut min_heap = BinaryHeap::new();

    let nums = vec![10, 20, 30];

    for &num in &nums {
        if max_heap.peek().unwrap() >= &num {
            max_heap.push(num);
        } else {
            min_heap.push(-num);
        }

        if max_heap.len() > min_heap.len() + 1 {
            if let Some(top) = max_heap.pop() {
                min_heap.push(-top);
            }
        } else if min_heap.len() > max_heap.len() {
            if let Some(top) = min_heap.pop() {
                max_heap.push(-top);
            }
        }
    }

    println!("Median: {}", max_heap.peek().unwrap());
}
APanic at unwrap on empty max_heap.peek() during first iteration
BCompile error due to missing type annotations
CIncorrect median because min_heap stores negative values but comparison is wrong
DNo error, prints correct median
Attempts:
2 left
💡 Hint
Check what happens when max_heap.peek() is called before any element is inserted.
📝 Syntax
advanced
1:30remaining
Which option fixes the syntax error in this Rust median finder snippet?
Fix the syntax error in this Rust code snippet for inserting into heaps:
DSA Rust
if max_heap.peek().map_or(true, |&x| num <= x) {
    max_heap.push(num)
} else {
    min_heap.push(-num)
}
AChange max_heap.push(num) to max_heap.push(&num)
BReplace map_or with unwrap_or_else
C
Add semicolons after push calls:
max_heap.push(num);
min_heap.push(-num);
DRemove else block entirely
Attempts:
2 left
💡 Hint
Rust statements need semicolons unless they are the last expression.
🚀 Application
expert
2:30remaining
How many elements are in each heap after inserting this sequence?
Using two heaps to find median, after inserting the numbers [8, 12, 10, 5, 7, 6], how many elements are in the max-heap and min-heap respectively?
Amax-heap: 3, min-heap: 3
Bmax-heap: 4, min-heap: 2
Cmax-heap: 2, min-heap: 4
Dmax-heap: 5, min-heap: 1
Attempts:
2 left
💡 Hint
Balance heaps so max-heap can have at most one more element than min-heap.

Practice

(1/5)
1. What is the main purpose of using two heaps (a max-heap and a min-heap) in the Median of Data Stream problem?
easy
A. To sort the entire data stream before finding the median
B. To store all elements in one heap and ignore the other
C. To efficiently find the median by balancing smaller and larger halves of the data
D. To use heaps only for insertion speed without median calculation

Solution

  1. Step 1: Understand the role of two heaps

    The max-heap stores the smaller half of the numbers, and the min-heap stores the larger half.
  2. Step 2: How this helps find the median

    Balancing these heaps allows quick access to the middle values, enabling efficient median calculation.
  3. Final Answer:

    To efficiently find the median by balancing smaller and larger halves of the data -> Option C
  4. Quick Check:

    Two heaps balance halves = median found fast [OK]
Hint: Two heaps split data into halves for quick median [OK]
Common Mistakes:
  • Thinking heaps sort all data fully
  • Using only one heap for median
  • Ignoring balancing heaps after insertion
2. Which Rust data structure is best suited to implement a max-heap for the Median of Data Stream problem?
easy
A. BinaryHeap (max-heap by default)
B. HashMap storing counts of elements
C. Vec with manual sorting after each insertion
D. LinkedList for fast insertion and removal

Solution

  1. Step 1: Identify Rust's heap implementation

    Rust's standard library provides BinaryHeap which is a max-heap by default.
  2. Step 2: Using Reverse wrapper for min-heap

    To create a min-heap, BinaryHeap with Reverse wrapper is used; for max-heap, BinaryHeap alone suffices.
  3. Final Answer:

    BinaryHeap (max-heap by default) -> Option A
  4. Quick Check:

    BinaryHeap = max-heap in Rust [OK]
Hint: Rust BinaryHeap is max-heap by default [OK]
Common Mistakes:
  • Using Vec and sorting every time (slow)
  • Confusing HashMap with heap
  • Using LinkedList which is not a heap
3. What will be the median after inserting the numbers 5, 15, 1, 3 in order using two heaps?
medium
A. 6
B. 5
C. 3
D. 4

Solution

  1. Step 1: Insert 5 and find median

    Max-heap: [5], Min-heap: [], median = 5
  2. Step 2: Insert 15 and balance heaps

    Max-heap: [5], Min-heap: [15], median = (5+15)/2 = 10
  3. Step 3: Insert 1 and rebalance

    Max-heap: [5,1], Min-heap: [15], median = 5
  4. Step 4: Insert 3 and rebalance

    Max-heap: [3,1], Min-heap: [5,15], median = (3+5)/2 = 4
  5. Final Answer:

    4 -> Option D
  6. Quick Check:

    Median after 4 inserts = 4 [OK]
Hint: Balance heaps after each insert, median is middle value(s) [OK]
Common Mistakes:
  • Not balancing heaps after insertion
  • Taking median as last inserted number
  • Incorrect average calculation for even count
4. Given this Rust snippet for adding a number to heaps, what is the bug?
if num <= *max_heap.peek().unwrap() {
    max_heap.push(num);
} else {
    min_heap.push(num);
}

if max_heap.len() > min_heap.len() + 1 {
    let val = max_heap.pop().unwrap();
    min_heap.push(val);
} else if min_heap.len() > max_heap.len() {
    let val = min_heap.pop().unwrap();
    max_heap.push(val);
}
medium
A. Missing check for empty max_heap before peek() causing panic
B. Heaps are not balanced after insertion
C. Should pop from min_heap when max_heap is larger
D. No bug, code balances heaps correctly

Solution

  1. Step 1: Analyze peek() usage on max_heap

    Calling peek() on an empty max_heap causes unwrap() panic because there is no element.
  2. Step 2: Identify missing empty check

    Code should check if max_heap is empty before peek() to avoid runtime error.
  3. Final Answer:

    Missing check for empty max_heap before peek() causing panic -> Option A
  4. Quick Check:

    peek() on empty heap = panic without check [OK]
Hint: Always check heap is not empty before peek() [OK]
Common Mistakes:
  • Assuming heaps always have elements before peek()
  • Confusing which heap to pop from when balancing
  • Ignoring unwrap() panic possibility
5. How would you modify the two heaps approach to efficiently find the median if the data stream can contain duplicate numbers and you want to remove numbers as well?
hard
A. Use only one heap and sort after every insertion and removal
B. Use two heaps plus a hash map to track counts and lazy removal of elements
C. Use a balanced binary search tree instead of heaps
D. Ignore duplicates and only keep unique numbers in heaps

Solution

  1. Step 1: Understand problem with duplicates and removals

    Heaps alone cannot remove arbitrary elements efficiently, especially duplicates.
  2. Step 2: Use hash map for counts and lazy removal

    Track counts of elements in a hash map and mark elements for removal without immediate heap deletion.
  3. Step 3: Clean heaps lazily during median calculation

    Remove invalid elements from heap tops lazily to maintain correct median.
  4. Final Answer:

    Use two heaps plus a hash map to track counts and lazy removal of elements -> Option B
  5. Quick Check:

    Heaps + hash map = efficient median with removals [OK]
Hint: Combine heaps with hash map for removals and duplicates [OK]
Common Mistakes:
  • Trying to remove elements directly from heaps
  • Ignoring duplicates in median calculation
  • Using only sorting which is inefficient
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard