Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push a value onto the stack.
DSA Rust
fn push(&mut self, val: i32) {
self.stack.push([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing the wrong variable instead of 'val'.
Using stack length instead of the value.
✗ Incorrect
We push the given value 'val' onto the main stack.
2fill in blank
mediumComplete the code to get the current minimum value from the min stack.
DSA Rust
fn get_min(&self) -> Option<i32> {
self.min_stack.[1]().copied()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes the element.
Using 'first' which gets the bottom element.
✗ Incorrect
The 'last' method returns the top element of the min stack without removing it.
3fill in blank
hardFix the error in the pop method to correctly update both stacks.
DSA Rust
fn pop(&mut self) -> Option<i32> {
let val = self.stack.pop()?;
if val == *self.min_stack.[1]().unwrap() {
self.min_stack.pop();
}
Some(val)
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes the element prematurely.
Using 'first' which checks the wrong element.
✗ Incorrect
We compare with the top of min_stack using 'last' without removing it.
4fill in blank
hardFill both blanks to correctly update the min stack when pushing a new value.
DSA Rust
fn push(&mut self, val: i32) {
self.stack.push(val);
if self.min_stack.is_empty() || val [1] *self.min_stack.[2]().unwrap() {
self.min_stack.push(val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '>=' instead of '<=' causing wrong min updates.
Using 'first' instead of 'last' to peek top element.
✗ Incorrect
We push 'val' to min_stack if it is less than or equal to the current minimum (top of min_stack).
5fill in blank
hardFill the blank to implement a method that returns the top element of the stack safely.
DSA Rust
fn top(&self) -> Option<i32> {
self.stack.[1]().copied()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' which removes the element.
Using 'first' which gets the bottom element.
✗ Incorrect
The 'last' method returns the top element without removing it, and 'copied' converts from reference to value.
