Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a max heap using Rust's BinaryHeap.
DSA Rust
let mut max_heap = std::collections::BinaryHeap::new(); max_heap.[1](10);
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push
Using peek which only views the top element
✗ Incorrect
The push method adds an element to the heap.
2fill in blank
mediumComplete the code to get the smallest element from a min heap simulated by a max heap in Rust.
DSA Rust
let mut min_heap = std::collections::BinaryHeap::new(); min_heap.push(-5); min_heap.push(-10); let smallest = -min_heap.[1]().unwrap();
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek which does not remove the element
Using push which adds elements
✗ Incorrect
pop removes and returns the top element, which is the smallest when values are negated.
3fill in blank
hardFix the error in balancing the two heaps by moving the top element from max_heap to min_heap.
DSA Rust
if max_heap.len() > min_heap.len() + 1 { let val = max_heap.[1]().unwrap(); min_heap.push(-val); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek which does not remove the element
Using push which adds elements
✗ Incorrect
pop removes the top element so it can be moved to the other heap.
4fill in blank
hardFill both blanks to calculate the median when heaps have equal size.
DSA Rust
if max_heap.len() == min_heap.len() { median = (max_heap.[1]().unwrap() + (-min_heap.[2]().unwrap())) as f64 / 2.0; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop which removes elements
Using len which returns size, not element
✗ Incorrect
peek returns the top element without removing it, needed to calculate median.
5fill in blank
hardFill all three blanks to insert a new number and balance the heaps correctly.
DSA Rust
if max_heap.len() == 0 || num <= max_heap.[1]().unwrap() { max_heap.[2](num); } else { min_heap.[3](-num); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push
Using len instead of peek for comparison
✗ Incorrect
peek checks the top element, push adds the new number to the correct heap.
