Bird
Raised Fist0
DSA C++programming

Peek Top Element of Stack in DSA C++

Choose your learning style10 modes available
Mental Model
A stack is like a pile of plates where you only see and use the top plate. Peeking means looking at the top plate without removing it.
Analogy: Imagine a stack of books on a table. You can only see and touch the top book. Peeking is just looking at the title of the top book without taking it off.
Stack (top on right): bottom -> 1 -> 2 -> 3 -> [top↑]
Dry Run Walkthrough
Input: stack: push 1, push 2, push 3; peek top element
Goal: Find the value of the top element without removing it
Step 1: push 1 onto empty stack
bottom -> [1↑]
Why: Start with one element; it becomes the top
Step 2: push 2 onto stack
bottom -> 1 -> [2↑]
Why: New element goes on top, previous top moves down
Step 3: push 3 onto stack
bottom -> 1 -> 2 -> [3↑]
Why: Add another element on top
Step 4: peek top element
bottom -> 1 -> 2 -> [3↑]
Why: Look at top without removing it
Result:
bottom -> 1 -> 2 -> [3↑]
Top element is 3
Annotated Code
DSA C++
#include <iostream>
#include <stack>
#include <stdexcept>

using namespace std;

int peekTop(stack<int> &st) {
    if (st.empty()) {
        throw runtime_error("Stack is empty");
    }
    return st.top(); // return top element without removing
}

int main() {
    stack<int> st;
    st.push(1); // push 1
    st.push(2); // push 2
    st.push(3); // push 3

    try {
        int topElement = peekTop(st); // peek top
        cout << "Top element is " << topElement << endl;
    } catch (const exception &e) {
        cout << e.what() << endl;
    }
    return 0;
}
if (st.empty()) { throw runtime_error("Stack is empty"); }
Check if stack is empty to avoid error
return st.top(); // return top element without removing
Access top element without changing stack
OutputSuccess
Top element is 3
Complexity Analysis
Time: O(1) because accessing the top element of a stack is a direct operation
Space: O(n) because the stack stores n elements; peeking does not use extra space
vs Alternative: Compared to popping which removes the element, peeking is faster and safer when you only need to see the top
Edge Cases
empty stack
throws an error indicating the stack is empty
DSA C++
if (st.empty()) { throw runtime_error("Stack is empty"); }
When to Use This Pattern
When a problem asks for the current top value without removing it, use the peek operation on a stack to get it instantly.
Common Mistakes
Mistake: Using pop() to get the top element which removes it
Fix: Use top() to peek without removing the element
Summary
Peek returns the top element of the stack without removing it.
Use peek when you need to see the last added item but keep it in the stack.
The key is that peek looks at the top without changing the stack.

Practice

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

Solution

  1. Step 1: Understand stack operations

    A stack is a collection where elements are added or removed from the top only.
  2. Step 2: Define peek operation

    The peek operation returns the top element without removing it, unlike pop which removes it.
  3. Final Answer:

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

    peek() = top element [OK]
Hint: Peek shows top without removal [OK]
Common Mistakes:
  • Confusing peek with pop
  • Thinking peek adds elements
  • Assuming peek checks emptiness
2. Which of the following is the correct syntax to peek the top element of a stack named stk in C++ STL?
easy
A. stk.pop();
B. stk.peek();
C. stk.top();
D. stk.getTop();

Solution

  1. Step 1: Recall C++ STL stack methods

    The standard method to access the top element is top().
  2. Step 2: Identify correct syntax

    stk.top(); returns the top element without removing it.
  3. Final Answer:

    stk.top(); -> Option C
  4. Quick Check:

    stk.top() = peek top element [OK]
Hint: Use .top() to peek in C++ STL stack [OK]
Common Mistakes:
  • Using .peek() which is not in C++ STL
  • Using .pop() which removes element
  • Using non-existent .getTop() method
3. What will be the output of the following C++ code?
std::stack<int> stk;
stk.push(10);
stk.push(20);
stk.push(30);
std::cout << stk.top() << std::endl;
medium
A. 30
B. 10
C. 20
D. Compilation error

Solution

  1. Step 1: Trace push operations

    Elements pushed in order: 10, then 20, then 30. Stack top is last pushed element 30.
  2. Step 2: Check top() output

    stk.top() returns 30 without removing it.
  3. Final Answer:

    30 -> Option A
  4. Quick Check:

    Last pushed = top = 30 [OK]
Hint: Top is last pushed element [OK]
Common Mistakes:
  • Confusing top with bottom element
  • Assuming top removes element
  • Thinking output is 20 or 10
4. Identify the error in the following code snippet that tries to peek the top element of a stack named stk:
int topElement = stk.peek();
medium
A. stk should be declared as a queue
B. peek() is not a valid method in C++ STL stack
C. topElement should be a pointer
D. stk.pop() should be used instead

Solution

  1. Step 1: Check method availability in C++ STL stack

    C++ STL stack does not have a method named peek().
  2. Step 2: Correct method to peek top element

    The correct method is top(), so stk.top() should be used.
  3. Final Answer:

    peek() is not a valid method in C++ STL stack -> Option B
  4. Quick Check:

    Use stk.top() not stk.peek() [OK]
Hint: Use .top(), not .peek() in C++ STL [OK]
Common Mistakes:
  • Using peek() method which doesn't exist
  • Confusing pop() with peek()
  • Thinking topElement must be pointer
5. Given a stack stk with elements [5, 10, 15] pushed in that order, which code snippet correctly prints the top element without removing it and then prints the stack size?
hard
A. std::cout << stk.pop() << std::endl; std::cout << stk.size() << std::endl;
B. std::cout << stk.top() << std::endl; stk.pop(); std::cout << stk.size() << std::endl;
C. std::cout << stk.peek() << std::endl; std::cout << stk.size() << std::endl;
D. std::cout << stk.top() << std::endl; std::cout << stk.size() << std::endl;

Solution

  1. Step 1: Understand peek without removal

    To peek, use stk.top() which returns top element without removing it.
  2. Step 2: Check stack size after peek

    Since peek does not remove, stk.size() remains 3.
  3. Final Answer:

    std::cout << stk.top() << std::endl; std::cout << stk.size() << std::endl; -> Option D
  4. Quick Check:

    top() no removal + size() correct [OK]
Hint: Use top() to peek, size() unchanged [OK]
Common Mistakes:
  • Using pop() which removes element
  • Using peek() which is invalid in C++ STL
  • Printing size after pop() expecting no change
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