Bird
Raised Fist0
DSA Rustprogramming~20 mins

Peek Top Element of Stack in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stack Peek Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of peeking the top element in this stack?

Consider a stack implemented using a vector in Rust. What will be printed after peeking the top element?

DSA Rust
fn main() {
    let mut stack = vec![10, 20, 30];
    if let Some(top) = stack.last() {
        println!("Top element: {}", top);
    } else {
        println!("Stack is empty");
    }
}
ATop element: 30
BTop element: 10
CStack is empty
DTop element: 20
Attempts:
2 left
💡 Hint

Remember that the last element in the vector represents the top of the stack.

❓ Predict Output
intermediate
2:00remaining
What happens when peeking an empty stack?

What will be the output of the following Rust code that tries to peek the top element of an empty stack?

DSA Rust
fn main() {
    let stack: Vec<i32> = Vec::new();
    match stack.last() {
        Some(top) => println!("Top element: {}", top),
        None => println!("Stack is empty"),
    }
}
AStack is empty
BTop element: 0
CPanic at runtime
DTop element: None
Attempts:
2 left
💡 Hint

Check what last() returns when the vector is empty.

🔧 Debug
advanced
3:00remaining
Why does this peek operation cause a panic?

Identify the reason for the panic in the following Rust code when peeking the top element of a stack.

DSA Rust
fn main() {
    let stack = vec![1, 2, 3];
    let top = stack.last().unwrap();
    println!("Top element: {}", top);
    let empty_stack: Vec<i32> = Vec::new();
    let top_empty = empty_stack.last().unwrap();
    println!("Top element: {}", top_empty);
}
Alast() method does not exist for Vec
BCalling unwrap() on None causes panic
CUsing println! macro incorrectly
DStack vector is not mutable
Attempts:
2 left
💡 Hint

Check what unwrap() does when called on None.

🧠 Conceptual
advanced
1:30remaining
What is the time complexity of peeking the top element in a stack implemented with a vector?

Consider a stack implemented using a vector in Rust. What is the time complexity of the peek operation (accessing the top element)?

AO(n^2) - Quadratic time
BO(n) - Linear time
CO(log n) - Logarithmic time
DO(1) - Constant time
Attempts:
2 left
💡 Hint

Think about how vectors store elements and how last() works.

🚀 Application
expert
3:00remaining
After these operations, what is the top element of the stack?

Given the following Rust code that performs push and pop operations on a stack, what will be the top element after all operations?

DSA Rust
fn main() {
    let mut stack = Vec::new();
    stack.push(5);
    stack.push(10);
    stack.pop();
    stack.push(20);
    stack.push(15);
    stack.pop();
    if let Some(top) = stack.last() {
        println!("Top element: {}", top);
    } else {
        println!("Stack is empty");
    }
}
ATop element: 15
BStack is empty
CTop element: 20
DTop element: 10
Attempts:
2 left
💡 Hint

Dry run the push and pop operations step by step.

Practice

(1/5)
1. What does the peek operation do in a stack data structure?
easy
A. Returns the top element without removing it
B. Removes the top element and returns it
C. Adds a new element to the top
D. Checks if the stack is empty

Solution

  1. Step 1: Understand stack operations

    A stack stores elements in a last-in, first-out order. Common operations include push, pop, and peek.
  2. Step 2: Define peek operation

    Peek returns the top element without removing it, allowing you to see the current top value safely.
  3. Final Answer:

    Returns the top element without removing it -> Option A
  4. Quick Check:

    Peek = top element without removal [OK]
Hint: Peek shows top without changing stack [OK]
Common Mistakes:
  • Confusing peek with pop operation
  • Thinking peek adds elements
  • Assuming peek checks emptiness
2. Which of the following Rust code snippets correctly peeks the top element of a stack implemented as a Vec<i32> named stack?
easy
A. let top = stack.last();
B. let top = stack[0];
C. let top = stack.pop();
D. let top = stack.first();

Solution

  1. Step 1: Understand Rust Vec methods for stack

    In Rust, Vec can be used as a stack. pop() removes and returns the last element, last() returns a reference to the last element without removing it.
  2. Step 2: Identify correct peek method

    Peek means to see the top element without removing it, so stack.last() is correct. stack.pop() removes it, stack[0] accesses the first element, and stack.first() returns the first element, not the top.
  3. Final Answer:

    let top = stack.last(); -> Option A
  4. Quick Check:

    Peek = stack.last() [OK]
Hint: Use .last() to peek top element in Rust Vec stack [OK]
Common Mistakes:
  • Using pop() which removes element
  • Accessing first() instead of last()
  • Using index 0 which is bottom of stack
3. What will be the output of the following Rust code?
let mut stack = vec![10, 20, 30];
if let Some(top) = stack.last() {
    println!("{}", top);
} else {
    println!("Stack is empty");
}
medium
A. 20
B. 30
C. 10
D. Stack is empty

Solution

  1. Step 1: Understand stack contents and last()

    The stack vector contains [10, 20, 30]. The last element is 30.
  2. Step 2: Trace the if let statement

    The stack.last() returns Some(&30), so the if block prints 30.
  3. Final Answer:

    30 -> Option B
  4. Quick Check:

    stack.last() = 30 [OK]
Hint: stack.last() returns top element reference [OK]
Common Mistakes:
  • Printing bottom element instead of top
  • Confusing last() with pop() output
  • Assuming stack is empty
4. Identify the error in the following Rust code that tries to peek the top element of a stack and fix it:
let stack = vec![1, 2, 3];
let top = stack.pop().unwrap();
println!("Top element: {}", top);
medium
A. No error, code works correctly
B. pop() removes element; use last() to peek instead
C. unwrap() causes panic; use expect() instead
D. stack should be mutable to use pop()

Solution

  1. Step 1: Check mutability for pop()

    pop() removes the last element, so the vector must be mutable. Here, stack is immutable.
  2. Step 2: Fix by making stack mutable

    Change let stack = vec![1, 2, 3]; to let mut stack = vec![1, 2, 3]; to allow pop().
  3. Final Answer:

    stack should be mutable to use pop() -> Option D
  4. Quick Check:

    pop() needs mutable stack [OK]
Hint: pop() requires mutable stack variable [OK]
Common Mistakes:
  • Ignoring mut keyword error
  • Confusing pop() with peek operation
  • Assuming unwrap() always safe
5. Given a stack implemented as Vec<i32>, write a Rust function peek_top that returns the top element as Option<i32> without removing it. What is the correct implementation?
hard
A. fn peek_top(stack: &mut Vec<i32>) -> Option<i32> { stack.pop() }
B. fn peek_top(stack: &Vec<i32>) -> i32 { *stack.last().unwrap() }
C. fn peek_top(stack: &Vec<i32>) -> Option<i32> { stack.last().copied() }
D. fn peek_top(stack: Vec<i32>) -> Option<i32> { stack.first().copied() }

Solution

  1. Step 1: Understand function requirements

    The function must peek without removing, so it should borrow stack immutably and return Option<i32>.
  2. Step 2: Analyze options

    fn peek_top(stack: &Vec<i32>) -> Option<i32> { stack.last().copied() } uses stack.last().copied() which returns Option<i32> by copying the reference. fn peek_top(stack: &mut Vec<i32>) -> Option<i32> { stack.pop() } removes element (pop), fn peek_top(stack: &Vec<i32>) -> i32 { *stack.last().unwrap() } unwraps and returns i32 (not Option), fn peek_top(stack: Vec<i32>) -> Option<i32> { stack.first().copied() } uses first() which is bottom element.
  3. Final Answer:

    fn peek_top(stack: &Vec<i32>) -> Option<i32> { stack.last().copied() } -> Option C
  4. Quick Check:

    Peek returns Option with copied last element [OK]
Hint: Use last().copied() for safe peek returning Option<i32> [OK]
Common Mistakes:
  • Using pop() which removes element
  • Returning i32 instead of Option<i32>
  • Accessing first() instead of last()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard