Bird
0
0
DSA Cprogramming~5 mins

Peek Top Element of Stack in DSA C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Peek Top Element of Stack
O(1)
Understanding Time Complexity

We want to understand how long it takes to look at the top item of a stack.

The question is: How does the time to peek change as the stack grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Peek top element of stack
int peek(int stack[], int top) {
    if (top == -1) {
        return -1; // stack empty
    }
    return stack[top];
}
    

This code returns the top element of the stack without removing it.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing the element at the top index.
  • How many times: Exactly once per peek call.
How Execution Grows With Input

Looking at the top element takes the same time no matter how big the stack is.

Input Size (n)Approx. Operations
101
1001
10001

Pattern observation: The time stays constant as the stack size grows.

Final Time Complexity

Time Complexity: O(1)

This means peeking the top element takes the same short time no matter how many items are in the stack.

Common Mistake

[X] Wrong: "Peeking takes longer if the stack is bigger because it has more items to check."

[OK] Correct: Peeking only looks at one position, the top, so it does not depend on stack size.

Interview Connect

Knowing that peek is a constant time operation helps you explain stack efficiency clearly and confidently.

Self-Check

"What if the stack was implemented as a linked list instead of an array? How would the time complexity of peek change?"