Stack matching
A stack remembers openers in last-in-first-out order, so the top is always the newest bracket still waiting to close. Reach for it whenever the most recent unfinished thing must finish first — matching brackets, undo, nested calls.
Stack
step 1 / 11
(
[0]{
[1][
[2]]
[3]}
[4])
[5]Input "({[]})". Valid means every closer matches the newest unclosed opener. A stack tracks exactly that. Stack: empty.
- i=0· arr[0] = (
Pseudocode
1FUNCTION isValid(s):2 make an empty stack3 FOR each position i from 0 to the length of s:4 ch = s[i]5 IF ch is an opener '(' or '{' or '[':6 push ch onto the stack7 ELSE IF popping the top does not equal the matching opener of ch:8 RETURN false9 END IF10 END FOR11 RETURN whether the stack is now empty12END FUNCTION
← / → step · space play · Home restart
Every step in words
Show all 11 steps
- Input "({[]})". Valid means every closer matches the newest unclosed opener. A stack tracks exactly that. Stack: empty.
- '(' is an opener — nothing to match yet, so remember it: push. Stack: (
- '{' also opens. Push on top — the newest opener must be the first to close. Stack: ( {
- '[' opens too. Push. Three openers now wait, '[' on top. Stack: ( { [
- ']' is a closer. It can only pair with the newest open bracket — whatever sits on top of the stack.
- Pop the top: '['. It matches ']' — pair closed, both retire. Stack: ( {
- '}' closes next. Top of stack is '{' — the newest bracket still open — so that's who it must match.
- Pop '{' — matches '}'. The nesting is unwinding in perfect reverse order. Stack: (
- Last char ')' — a closer. Only '(' remains on the stack, pushed first, closing last.
- Pop '(' — matches ')'. Every opener found its closer. Stack: empty.
- Loop done, stack empty — no opener left hanging. Return true: "({[]})" is valid.
Now solve it yourself
Watching is the first half. The second is writing it without the animation.