Ever wondered why computers need a stack to check if parentheses are balanced? Let’s see it in action with a metaphor that makes it impossible to forget.
Slide 1 — The Dressing Room Rule
You try on clothes in layers. You can only take off the last one you put on.
The Basic Rule
Action Log
State
With a single type of clothing, a simple counter tells us if the sequence is valid: just track how many items are on.
Slide 2 — A Valid Sequence
All garments come on and off in the correct order. Notice the counter going up and down.
Valid Sequence
Action Log
State
✅ We never try to remove a garment that wasn’t on top.
Slide 3 — The Impossible Sequence
What happens when we try to remove a garment that’s not on top?
Is this possible?
Action Log
State
With only one type, the counter catches this: we go negative! But what if we have multiple types?
Slide 4 — Multiple Types: T-Shirt, Sweater, Jacket
Now we introduce different garment types. Each has a different shape:
- T - T-Shirt (basic)
- S - Sweater (long sleeves)
- J - Jacket (open front)
Multiple Types - Valid Nesting
Action Log
State
With multiple types, we need to remember WHAT was put on last, not just count!
Slide 5 — The Tricky Example
Here’s the catch: the count per type might look balanced, but the sequence is impossible.
Counters look fine... but is it?
Action Log
State
❌ You can’t remove the T-Shirt when the Sweater is on top!
The counters say everything is fine (1 T, 1 S on), but order matters.
Slide 6 — The Final Reveal: Parentheses!
Now watch the labels transform…
Balanced Parentheses = Dressing in Layers
Action Log
State
The sequence ([{}]) is the same as putting on T-Shirt, Sweater, Jacket and
taking them off in reverse!
(= PUT T-Shirt →)= TAKE OFF T-Shirt[= PUT Sweater →]= TAKE OFF Sweater{= PUT Jacket →}= TAKE OFF Jacket
The Insight
Balancing parentheses is exactly like getting dressed in layers without breaking the laws of physics.
A counter works for a single type, but with multiple types (like (), [],
{}), you need a stack to remember the order.
That’s why the classic “balanced parentheses” algorithm uses a stack: it’s simulating a dressing room! 🧥