Sub topic 10
Checking balanced brackets
This chapter assumes you know Python lists, loops, dictionaries, and the stack operations push, pop, and peek from earlier chapters. It shows how a stack checks that brackets are balanced.
The problem
A string is balanced when every opening bracket has a matching closing bracket of the same type, and the pairs nest properly. Compilers, editors, and JSON parsers all run this check.
{[()]}is balanced.([)]is not. The pairs overlap instead of nesting.((is not. Two openers never get closed.)(is not. A closer appears before any opener.
Why a stack fits
Nested pairs close in the reverse of the order they opened. The most recent unclosed opener must be the next one to close. That is last in, first out, so a stack tracks the open brackets directly.
The rules:
- On an opening bracket, push it.
- On a closing bracket, pop the top and check that it is the matching opener. If the stack is empty or the types differ, the string is unbalanced.
- Ignore all other characters.
- After the last character, the stack must be empty. Leftover openers were never closed.
The implementation
def is_balanced(text):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stack
print(is_balanced("{[()]}")) # True
print(is_balanced("([)]")) # FalseThe dictionary maps each closer to the opener it needs. In if not stack or stack.pop() != pairs[ch], the check not stack runs first. Short-circuit evaluation means pop() never runs on an empty list, so no IndexError occurs.
Tracing a failure
Trace ([)]:
| Character | Action | Stack after |
|---|---|---|
| `(` | push | `(` |
| `[` | push | `( [` |
| `)` | pop `[`, expected `(` | mismatch, return False |
The closer ) arrives while [ is on top. The innermost open bracket must close first, so the string fails.
Common errors
- Skipping the final check. Without
return not stack, the string((returnsTrue, because nothing ever failed. - Popping an empty stack. Input such as
)raisesIndexErrorunless you test for emptiness first. - Counting instead of stacking. One counter per bracket type accepts
([)], since each type is individually balanced. Only a stack catches wrong nesting order. - Treating other characters as errors. Letters, digits, and spaces should be ignored, as the code does.
Cost
Each character is pushed and popped at most once, so time is O(n). The stack can hold up to n items, as in ((((, so extra space is O(n).
Exercise
What does is_balanced return for the input "(()" and why?
Show answer
It returns False. The two "(" characters are pushed, and the ")" pops one of them. The loop then ends with one "(" still on the stack, so not stack is False.
Exercise
Why does the string "([)]" pass a per-type counter check but fail the stack check?
Show answer
Each bracket type has equal opening and closing counts, so counters see no problem. The stack also requires correct nesting order. When ")" arrives, the top of the stack is "[", which does not match, so the check fails.