progress

~/problems / Stacks / Stacks

Valid Parentheses

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

A code editor highlights a line in red when its brackets don't line up. Write is_balanced(s) that returns whether the brackets in s are balanced.

s holds only ( ) [ ] { }. Every opener must be closed by the same kind, last opened first closed, and no closer may appear without an opener. "" is balanced.

is_balanced("([]{})")   # True
is_balanced("{[()()]}") # True
is_balanced("([)]")     # False   (the "[" is closed by ")")
is_balanced("((")       # False   (never closed)
is_balanced("])")       # False   (nothing to close)
is_balanced("")         # True

Up to 2 * 10^5 characters. ⭐ Bonus: a speed test earns a star for a single O(n) pass.

Show hint

a closer can only match the most recent unmatched opener. What structure hands you "the most recent thing" in O(1)?

Topic: Stacks. Matching pairs, undo history and evaluating expressions with a stack.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc