Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize an empty stack for indices.
DSA Rust
let mut stack: Vec<usize> = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using vec![] works but is less explicit in this context.
Using Vec::with_capacity(10) preallocates but is not necessary here.
✗ Incorrect
Vec::new() creates a new empty vector which we use as a stack to store indices.
2fill in blank
mediumComplete the code to pop the top index from the stack safely.
DSA Rust
if let Some(top) = stack.[1]() {
Attempts:
3 left
💡 Hint
Common Mistakes
remove() requires an index and is not used for stack pop.
pop_back() does not exist for Vec in Rust.
✗ Incorrect
pop() removes and returns the last element from the vector, which is the top of the stack.
3fill in blank
hardFix the error in the condition to check if current height is greater than height at stack top.
DSA Rust
while !stack.is_empty() && height[i] > height[[1]] {
Attempts:
3 left
💡 Hint
Common Mistakes
stack.last() returns an Option, not an index.
stack[stack.len()] is out of bounds and causes panic.
✗ Incorrect
stack[stack.len() - 1] accesses the last element index in the stack correctly.
4fill in blank
hardFill both blanks to calculate the distance and bounded height for trapped water.
DSA Rust
let distance = i - [1] - 1; let bounded_height = std::cmp::min(height[i], height[[2]]) - height[top];
Attempts:
3 left
💡 Hint
Common Mistakes
Using stack[stack.len() - 2] for distance accesses the index before the new top.
Using stack[0] does not represent the new top.
✗ Incorrect
Distance is between current index and the new top after popping (stack[stack.len() - 1]). Bounded height uses min of current height and height at new top (stack.last().copied().unwrap()).
5fill in blank
hardFill all three blanks to push current index and update total trapped water.
DSA Rust
stack.[1](i); total_water += distance * [2]; let top = [3];
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push to add index causes logic error.
Not unwrapping pop() causes type mismatch.
✗ Incorrect
We push current index i onto stack, add trapped water by multiplying distance and bounded_height, and pop top index from stack.
