Peek Top Element of Stack in DSA Python - Time & Space Complexity
We want to understand how long it takes to look at the top item of a stack.
Specifically, how the time changes as the stack grows bigger.
Analyze the time complexity of the following code snippet.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def peek(self):
return self.items[-1] if self.items else None
This code defines a stack and shows how to peek at the top element without removing it.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the last element of the list (stack top).
- How many times: Exactly once per peek call, no loops or recursion.
Looking at the top element takes the same amount of time no matter how big the stack is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The operation count stays the same as the stack grows.
Time Complexity: O(1)
This means peeking the top element takes a constant time regardless of stack size.
[X] Wrong: "Peeking takes longer if the stack is bigger because it has to look through all elements."
[OK] Correct: Peeking only looks at the last item directly, no need to check other elements.
Knowing that peek is a constant time operation helps you explain stack efficiency clearly in interviews.
"What if the stack was implemented using a linked list instead of a list? How would the time complexity of peek change?"