Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element into the stack using a queue.
DSA Rust
fn push(&mut self, x: i32) {
self.queue.push_back(x);
for _ in 0..self.queue.len() - 1 {
let val = self.queue.pop_front().unwrap();
self.queue.[1](val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop_back instead of push_back causes errors.
Using push_front changes the order incorrectly.
✗ Incorrect
We use push_back to add the element at the back of the queue after popping from the front to rotate the queue.
2fill in blank
mediumComplete the code to pop the top element from the stack.
DSA Rust
fn pop(&mut self) -> Option<i32> {
self.queue.[1]()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop_back returns the wrong element.
Using remove requires an index and is not suitable here.
✗ Incorrect
We pop from the front of the queue because the push operation rotates the queue to keep the top element at the front.
3fill in blank
hardFix the error in the peek method to return the top element without removing it.
DSA Rust
fn top(&self) -> Option<i32> {
self.queue.[1]().copied()
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pop_front removes the element.
Using get(0) returns an Option<&T>, but first() is more idiomatic.
✗ Incorrect
The first() method returns an Option reference to the first element without removing it.
4fill in blank
hardFill both blanks to check if the stack is empty.
DSA Rust
fn empty(&self) -> bool {
self.queue.[1]() [2] 0
}Attempts:
3 left
💡 Hint
Common Mistakes
Using len() != 0 returns the opposite of empty.
Using is_empty() == 0 is incorrect because is_empty() returns a bool.
✗ Incorrect
We use len() == 0 to check if the queue has no elements. Using is_empty() directly is better, but the code syntax requires comparison here.
5fill in blank
hardFill all three blanks to implement the push method that rotates the queue correctly.
DSA Rust
fn push(&mut self, x: i32) {
self.queue.[1](x);
for _ in 0..self.queue.[2]() - 1 {
let val = self.queue.[3]().unwrap();
self.queue.push_back(val);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using push_front instead of push_back changes order incorrectly.
Using pop_back instead of pop_front breaks rotation.
✗ Incorrect
We push_back the new element, then rotate by popping from the front and pushing back to keep the stack order.
