Stacks
What is a stack?
A collection where you add and remove only at the top: LIFO (last in, first out).
| Operation | Python list | Big O |
|---|---|---|
| push | stack.append(x) | O(1) |
| pop | stack.pop() | O(1) |
| peek | stack[-1] | O(1) |
| is empty | not stack | O(1) |
Where stacks appear
- Undo/redo in editors
- The browser back button
- The call stack: every function call is pushed, and popped when it returns (this is why deep recursion can "overflow")
- Matching brackets in code
- Evaluating expressions like
3 4 + 2 * - Depth-first search (Unit 10)
Pattern: balanced brackets
Push every opener. For each closer, the top of the stack must be the matching opener. At the end, the stack must be empty.
Pattern: monotonic stack
Keep the stack always increasing (or decreasing) to answer "next greater element" questions in O(n): pop smaller items whenever a bigger one arrives, because it is their answer.
⚠️ Popping from an empty stack raises an error, so check if stack: first.
Example
def balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
def next_greater(nums):
result = [-1] * len(nums)
stack = [] # indexes waiting for an answer
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
result[stack.pop()] = x
stack.append(i)
return result
print(balanced("{[()()]}"), balanced("(]"), balanced("((")) # True False False
print(next_greater([2, 1, 2, 4, 3])) # [4, 2, 4, -1, -1]