Pop Operation on Stack in DSA Python - Time & Space Complexity
We want to understand how long it takes to remove an item from 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 pop(self):
if not self.items:
return None
return self.items.pop()
This code removes the top item from the stack if it exists.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Removing the last item from the list.
- How many times: This happens once per pop call, no loops or recursion inside pop.
Removing the top item takes the same steps no matter how big the stack is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the stack grows.
Time Complexity: O(1)
This means popping an item takes a fixed amount of time regardless of stack size.
[X] Wrong: "Pop takes longer if the stack is bigger because it has more items."
[OK] Correct: Pop only removes the last item directly without checking others, so time does not grow with stack size.
Knowing that pop is a quick, 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 pop change?"