Balanced Brackets
Medium · 55 XPWrite is_balanced(s) returning True when every bracket ()[]{} is closed in the right order. Print the result for four test strings.
{[()]} True
{[(])} False
((())) True
(] False
Push opening brackets onto a stack; on a closer, the popped item must be its partner. The stack must be empty at the end.
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
for test in ("{[()]}", "{[(])}", "((()))", "(]"):
print(f"{test} {is_balanced(test)}")
Run your code to check it…
How to approach Balanced Brackets
Brackets must close in the reverse order they opened, which is exactly what a stack gives you: last in, first out. Push every opening bracket. On a closing bracket, pop the most recent opener and check that it is the matching partner.
A dictionary from each closer to its opener (")": "(" and so on) makes the check a single lookup. Two more rules finish it: a closer that arrives with an empty stack is unbalanced, and anything left on the stack at the end is unbalanced too.
Worked through on this data
- "{[()]}": push {, [, (. Then ) pops (, ] pops [, } pops {. The stack ends empty: True.
- "{[(])}": push {, [, (. Then ] pops ( , which is not its partner: False immediately.
- "(]": push (, then ] pops ( and fails: False. "((()))" balances: True.
Common mistakes
- Just counting openers and closers: "{[(])}" has equal counts of every type and still is not balanced.
- Calling
stack.pop()on an empty list raises an IndexError on input such as ")(". Checkif not stackfirst. - Returning True when the loop ends without checking the stack, so "((" passes.
Time and space
One pass with constant work per character: O(n) time, and O(n) space in the worst case when every character is an opener.
Where this shows up
Every code editor that highlights a mismatched bracket, and every parser for JSON, HTML or Python itself, runs a stack like this one.
Take it further
Return the index of the first character that breaks the balance instead of False, so an editor could underline it.