Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element into the queue using the first stack.
DSA Rust
fn enqueue(&mut self, value: i32) {
self.stack_in.[1](value);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push will remove elements instead of adding.
Using peek does not modify the stack.
✗ Incorrect
To add an element to the queue, we push it onto the input stack using the push method.
2fill in blank
mediumComplete the code to check if the queue is empty by checking both stacks.
DSA Rust
fn is_empty(&self) -> bool {
self.stack_in.is_empty() && self.stack_out.[1]()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using len instead of is_empty returns a number, not a boolean.
Checking only one stack misses elements in the other.
✗ Incorrect
The queue is empty only if both stacks are empty, so we check is_empty on both.
3fill in blank
hardFix the error in the dequeue method to correctly move elements from stack_in to stack_out.
DSA Rust
fn dequeue(&mut self) -> Option<i32> {
if self.stack_out.is_empty() {
while let Some(value) = self.stack_in.[1]() {
self.stack_out.push(value);
}
}
self.stack_out.pop()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using push on stack_in instead of pop causes infinite loop.
Using peek does not remove elements, so loop never ends.
✗ Incorrect
We pop elements from stack_in to move them to stack_out, reversing order for correct dequeue.
4fill in blank
hardFill both blanks to implement the peek method that returns the front element without removing it.
DSA Rust
fn peek(&mut self) -> Option<&i32> {
if self.stack_out.[1]() {
while let Some(value) = self.stack_in.[2]() {
self.stack_out.push(value);
}
}
self.stack_out.last()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using push instead of pop on stack_in causes errors.
Not checking if stack_out is empty leads to wrong peek.
✗ Incorrect
If stack_out is empty, move elements by popping from stack_in and pushing to stack_out, then peek last element.
5fill in blank
hardFill all three blanks to implement the clear method that empties both stacks.
DSA Rust
fn clear(&mut self) {
self.stack_in.[1]();
self.stack_out.[2]();
self.stack_in = Vec::new();
self.stack_out = Vec::new();
println!("Queue cleared: stack_in length = {}, stack_out length = {}", self.stack_in.[3](), self.stack_out.len());
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop repeatedly instead of clear is inefficient.
Using is_empty instead of len in println shows boolean, not count.
✗ Incorrect
Use clear() to empty stacks, then check length with len() to confirm they are empty.
