Stacks
Last in, first out - the most recent item is always on top.
- active this step
- visited / done
- result
- removed / popped
Push (
An opening bracket waits on the stack for its partner.
VARIABLES
- ch
- (
- stack
- ["("]
Intuition & complexity
The core mental model, trade-offs, and Big-O cost.
What it is
A stack supports push (add to the top) and pop (remove from the top) in O(1). A Python list with append and pop works as a stack.
Why it matters
Many problems must match or undo the most recent thing first - brackets, function calls, browser history.
Think of it like this
A stack of plates: you add to and take from the top only.
Use it when
- Matching pairs like brackets or tags
- Undoing back to the latest state
- Evaluating expressions
Avoid it when
- You need first in, first out - use a queue
- You need to search inside - a stack only exposes its top
Complexity cheatsheet
| Operation | Time | Space |
|---|---|---|
| Push | O(1) amortized | O(1) |
| Pop or peek the top | O(1) | O(1) |
| Search for a value | O(n) | O(1) |
Often confused with: monotonic stacks - a stack kept in sorted order to answer “next greater” questions.
How to recognize it
Clues in interview prompts that point straight to this pattern.
- Input that “opens” and “closes” things maps to push and pop
- Any recursion can be rewritten with an explicit stack
Mistakes & edge cases
Catch common off-by-one bugs and corner cases before submitting.
Common mistakes
- Popping from an empty stack on input like ")("
- Returning True without checking that the stack is empty at the end
- Using pop(0) - that’s a queue operation and O(n)
Edge cases to test
- Empty string - valid
- Only opening brackets like "((("
- A closing bracket first, like "]"
Knowledge check
Quick check to lock in the intuition.
For the input "(]", where does the check fail?
Practice
Apply what you just watched on real interview problems.