Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a max heap from the vector.
DSA Rust
let mut heap = std::collections::BinaryHeap::[1](nums);Attempts:
3 left
💡 Hint
Common Mistakes
Using new() creates an empty heap, not from a vector.
with_capacity() only reserves space, does not build from vector.
✗ Incorrect
We use BinaryHeap::from to create a max heap from an existing vector.
2fill in blank
mediumComplete the code to pop the largest element from the max heap.
DSA Rust
let largest = heap.[1]().unwrap();Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() only returns a reference, does not remove the element.
remove() and extract() are not methods of BinaryHeap.
✗ Incorrect
pop() removes and returns the largest element from the max heap.
3fill in blank
hardFix the error in the loop that pops k-1 largest elements.
DSA Rust
for _ in 0..[1] { heap.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Popping k times removes the kth largest too early.
Using k+1 or k*2 causes out of range or logic errors.
✗ Incorrect
We pop k-1 times to remove the top k-1 largest elements before getting the kth.
4fill in blank
hardFill both blanks to return the kth largest element safely.
DSA Rust
match heap.[1]() { Some(val) => val, None => [2], }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of pop() does not remove the element.
Returning 0 silently hides errors.
✗ Incorrect
pop() removes the top element; if heap is empty, panic with a message.
5fill in blank
hardFill all three blanks to implement kth_largest function using max heap.
DSA Rust
fn kth_largest(nums: Vec<i32>, k: usize) -> i32 {
let mut heap = std::collections::BinaryHeap::[1](nums);
for _ in 0..[2] {
heap.[3]();
}
heap.pop().expect("Heap is empty")
}Attempts:
3 left
💡 Hint
Common Mistakes
Using new() creates empty heap, not from nums.
Looping k times removes kth largest too early.
Using peek() instead of pop() does not remove elements.
✗ Incorrect
Create heap from vector, pop k-1 times, then pop kth largest element.
