Cheese with Holes (Emmental) - Developing
Cheese with Holes (Emmental) - Developing
Useful note with basic structure, but still has holes to fill.
Click the cheese icon to learn more

Balanced Dressing Room

Author: guiferviz

Created:

Last Modified:

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

PUT T-Shirt
PUT T-Shirt
TAKE OFF T-Shirt

State

Balance
0

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

PUT T-Shirt
PUT T-Shirt
TAKE OFF T-Shirt
PUT T-Shirt
TAKE OFF T-Shirt
TAKE OFF T-Shirt

State

Balance
0

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

PUT T-Shirt
PUT T-Shirt
TAKE OFF T-Shirt
TAKE OFF T-Shirt
TAKE OFF T-Shirt

State

Balance
0

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

PUT T-Shirt
PUT Sweater
PUT Jacket
TAKE OFF Jacket
TAKE OFF Sweater
TAKE OFF T-Shirt

State

Stack
empty

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

PUT T-Shirt
PUT Sweater
TAKE OFF T-Shirt

State

Balance
0
Stack
empty
By Type
T0
S0
J0

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

Stack
empty

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! 🧥