Challenge - 5 Problems
Stack Push Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateWhat is the output after pushing elements on the stack?
Consider the following Rust code that pushes elements onto a stack implemented using a vector. What will be printed after all push operations?
DSA Rust
fn main() {
let mut stack = Vec::new();
stack.push(10);
stack.push(20);
stack.push(30);
println!("{:?}", stack);
}Attempts:
2 left
💡 Hint
Remember that push adds elements to the end of the vector.
✗ Incorrect
The push method adds elements to the end of the vector. So the stack vector will contain elements in the order they were pushed: 10, then 20, then 30.
❓ Predict Output
intermediateWhat is the stack state after pushing and popping elements?
Given the Rust code below, what is the final state of the stack vector after all operations?
DSA Rust
fn main() {
let mut stack = Vec::new();
stack.push(5);
stack.push(15);
stack.pop();
stack.push(25);
println!("{:?}", stack);
}Attempts:
2 left
💡 Hint
Pop removes the last element pushed.
✗ Incorrect
The pop removes the last pushed element (15). So after popping, the stack has [5]. Then 25 is pushed, resulting in [5, 25].
🔧 Debug
advancedWhy does this Rust stack push code fail to compile?
Identify the error in the following Rust code that tries to push elements onto a stack and fix it.
DSA Rust
fn main() {
let stack = Vec::new();
stack.push(1);
println!("{:?}", stack);
}Attempts:
2 left
💡 Hint
Check if the vector is mutable before pushing.
✗ Incorrect
The vector stack is declared immutable by default. You cannot push to an immutable vector. Declaring it as let mut stack = Vec::new(); fixes the error.
🧠 Conceptual
advancedWhat is the time complexity of the push operation on a Rust Vec used as a stack?
When using a Rust vector as a stack, what is the average time complexity of the push operation?
Attempts:
2 left
💡 Hint
Consider how vectors resize internally.
✗ Incorrect
Push on a vector is usually O(1) amortized because resizing happens occasionally, but most pushes are constant time.
❓ Predict Output
expertWhat is the output after pushing elements in a loop on a Rust stack?
Analyze the Rust code below. What will be printed after the loop completes?
DSA Rust
fn main() {
let mut stack = Vec::new();
for i in 1..=4 {
stack.push(i * 2);
}
println!("{:?}", stack);
}Attempts:
2 left
💡 Hint
Check the multiplication inside the loop.
✗ Incorrect
The loop pushes i * 2 for i from 1 to 4, so the stack contains [2, 4, 6, 8].
