3. Stacks (Balanced Brackets)
Last in, first out. Push and pop at the top in O(1). Stacks power undo, function calls, expression parsing and bracket matching.
How it works
A stack only lets you touch the most recent item. That makes it perfect for anything nested: the innermost open bracket must be closed first, the most recent function call returns first.
Balanced brackets: scan left to right. Push every opening bracket. On a closing bracket, the top of the stack must be its matching opener; pop it. The string is balanced if no mismatch happens and the stack ends empty.
Diagram
flowchart TD
R["Read next char"] --> O{"Opening bracket?"}
O -->|yes| P["Push it"] --> R
O -->|no| C{"Top of stack is its opener?"}
C -->|yes| Q["Pop"] --> R
C -->|no| F["Unbalanced"]
R -->|no chars left| E{"Stack empty?"}
E -->|yes| T["Balanced"]
E -->|no| F
Step-by-step trace
Input: Check {[()()]}.
| i | char | Action | Stack (bottom -> top) |
|---|---|---|---|
| 0 | { |
push | { |
| 1 | [ |
push | {[ |
| 2 | ( |
push | {[( |
| 3 | ) |
pop ( (matches) |
{[ |
| 4 | ( |
push | {[( |
| 5 | ) |
pop ( (matches) |
{[ |
| 6 | ] |
pop [ (matches) |
{ |
| 7 | } |
pop { (matches) |
empty |
Result: Stack is empty at the end, so the string is balanced.
Complexity
| Operation | Time | Space |
|---|---|---|
| Push / pop / peek | O(1) | O(1) |
| Bracket check of length n | O(n) | O(n) |
Python reference implementation
def is_balanced(s):
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
Common mistakes and tips
- Check for an empty stack before popping;
)on its own must fail, not crash. - Forgetting the final
not stackcheck accepts strings like((. - A monotonic stack (kept increasing or decreasing) solves next-greater-element problems in O(n).
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Linked Lists (Reversal) | Next: Queues (Two-Stack Queue) |