Which scenario is best suited for using a Min Heap?
Think about which heap type helps you get the smallest element fast.
A Min Heap always keeps the smallest element at the top, making it ideal for priority queues where the smallest value is needed first.
Which use case fits best for a Max Heap?
Consider which heap type helps you get the largest element fast.
A Max Heap keeps the largest element at the top, making it perfect for priority queues where the highest value is needed first.
What is the state of the Min Heap after inserting these numbers in order: 7, 3, 5, 1?
use std::collections::BinaryHeap;
fn main() {
let mut min_heap = BinaryHeap::new();
min_heap.push(std::cmp::Reverse(7));
min_heap.push(std::cmp::Reverse(3));
min_heap.push(std::cmp::Reverse(5));
min_heap.push(std::cmp::Reverse(1));
let mut result = Vec::new();
while let Some(std::cmp::Reverse(val)) = min_heap.pop() {
result.push(val);
}
println!("{:?}", result);
}Remember that popping from a Min Heap returns elements from smallest to largest.
The Rust BinaryHeap is a Max Heap by default. Wrapping values with Reverse turns it into a Min Heap. Popping elements returns them in ascending order.
What will be printed after pushing these numbers into a Rust BinaryHeap and popping all elements: 2, 9, 4, 6?
use std::collections::BinaryHeap;
fn main() {
let mut max_heap = BinaryHeap::new();
max_heap.push(2);
max_heap.push(9);
max_heap.push(4);
max_heap.push(6);
let mut result = Vec::new();
while let Some(val) = max_heap.pop() {
result.push(val);
}
println!("{:?}", result);
}Rust's BinaryHeap is a Max Heap by default.
BinaryHeap in Rust pops the largest element first, so the output is descending order.
You want to maintain the median of a stream of numbers efficiently. Which combination of heaps is best?
Think about how to split numbers to get median quickly.
Using a Max Heap for the lower half and a Min Heap for the upper half allows quick access to the middle values, enabling efficient median calculation.
