Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a new empty stack for indices.
DSA Rust
let mut stack: Vec<usize> = Vec::new(); stack.[1](0);
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push will remove an element instead of adding.
Using insert or remove requires an index and is not typical for stack push.
✗ Incorrect
We use push to add an element to the top of the stack.
2fill in blank
mediumComplete the code to pop elements from the stack while the current price is higher than the price at the top index.
DSA Rust
while !stack.is_empty() && prices[i] > prices[stack.[1]()] { stack.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() removes the element, which is done later, not for comparison.
Using len() or first() does not give the top element.
✗ Incorrect
last() returns the last element of the vector without removing it, which is needed to compare prices.
3fill in blank
hardFix the error in calculating the span when the stack is empty.
DSA Rust
let span = if stack.is_empty() { [1] } else { i - stack.last().unwrap()[2] };
Attempts:
3 left
💡 Hint
Common Mistakes
Using i - 1 when stack is empty gives wrong span.
Adding 1 instead of subtracting 1 in else case causes off-by-one error.
✗ Incorrect
If the stack is empty, the span is i + 1. Otherwise, subtract the top index and subtract 1 to get the span.
4fill in blank
hardFill both blanks to correctly push the current index and update the span vector.
DSA Rust
spans.push(i - stack.last().unwrap()[1]); stack.[2](i);
Attempts:
3 left
💡 Hint
Common Mistakes
Using + 1 causes incorrect span calculation.
Using pop instead of push removes elements incorrectly.
✗ Incorrect
We subtract 1 to get the correct span length and push the current index onto the stack.
5fill in blank
hardFill all three blanks to complete the main loop for calculating stock spans.
DSA Rust
for i in 0..prices.len() { while !stack.is_empty() && prices[i] > prices[stack.[1]()] { stack.[2](); } let span = if stack.is_empty() { i [3] 1 } else { i - stack.last().unwrap() - 1 }; spans.push(span); stack.push(i); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop() instead of last() for peeking causes errors.
Subtracting 1 instead of adding 1 when stack is empty causes off-by-one error.
✗ Incorrect
We use last() to peek, pop() to remove, and add 1 to i when stack is empty for span calculation.
