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)?