Peek Top Element of Stack in DSA C - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the element at the top index.
- How many times: Exactly once per peek call.
Looking at the top element takes the same time no matter how big the stack is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant as the stack size grows.
Time Complexity: O(1)
This means peeking the top element takes the same short time no matter how many items are in the stack.
[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.
Knowing that peek is a constant time operation helps you explain stack efficiency clearly and confidently.
"What if the stack was implemented as a linked list instead of an array? How would the time complexity of peek change?"
