Push Operation on Stack in DSA Python - Time & Space Complexity
We want to understand how the time to add an item to a stack changes as the stack grows.
How does the push operation behave when the stack size increases?
Analyze the time complexity of the following code snippet.
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
This code adds an item to the top of the stack using a list's append method.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding one item to the end of the list (stack).
- How many times: Each push adds exactly one item, no loops or recursion involved.
Adding one item takes the same amount of time no matter how many items are already in the stack.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant as the stack grows.
Time Complexity: O(1)
This means adding an item to the stack takes the same short time no matter how big the stack is.
[X] Wrong: "Push takes longer as the stack grows because it has to move all items."
[OK] Correct: The push just adds to the end of the list without moving existing items, so time stays the same.
Knowing push is very fast helps you explain why stacks are great for quick add/remove tasks in real programs.
"What if the stack was implemented using a linked list instead of a list? How would the time complexity of push change?"