Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new empty stack.
DSA Rust
let mut stack: Vec<i32> = Vec::[1]();Attempts:
3 left
💡 Hint
Common Mistakes
Using Vec::with_capacity() without specifying capacity.
Using Vec::from() which requires an initial array or slice.
✗ Incorrect
The Vec::new() function creates a new empty vector which we use as the stack.
2fill in blank
mediumComplete the code to push an element onto the stack.
DSA Rust
stack.[1](10);
Attempts:
3 left
💡 Hint
Common Mistakes
Using insert() which requires an index.
Using append() which adds elements from another vector.
✗ Incorrect
The push() method adds an element to the end of the vector, acting like pushing onto the stack.
3fill in blank
hardFix the error in popping an element from the stack safely.
DSA Rust
let top = stack.[1]().unwrap_or(-1);
Attempts:
3 left
💡 Hint
Common Mistakes
Using last() which only returns a reference without removing.
Using remove() which requires an index.
✗ Incorrect
pop() removes and returns the last element, unwrap_or(-1) handles empty stack by returning -1.
4fill in blank
hardFill both blanks to check if the stack is empty and print a message.
DSA Rust
if stack.[1]() [2] 0 { println!("Stack is empty"); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using is_empty() without comparison.
Using != instead of == causing wrong condition.
✗ Incorrect
stack.len() returns the number of elements; comparing with == 0 checks if empty.
5fill in blank
hardFill all three blanks to implement a function that returns the top element without removing it.
DSA Rust
fn peek(stack: &Vec<i32>) -> Option<i32> {
stack.[1]().cloned().[2](|| [3])
}Attempts:
3 left
💡 Hint
Common Mistakes
Using unwrap() which panics if stack is empty.
Using pop() which removes the element.
✗ Incorrect
last() gets reference to last element, cloned() copies it, unwrap_or returns None if empty.
