Balanced brackets
Problem
Return True if every bracket among ()[]{} in s is properly matched and nested. Ignore all other characters.
Signature
def is_balanced(s: str) -> bool: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> is_balanced('([]{})') == True
True
>>> is_balanced('([)]') == False
TrueHints
Stack with a closing->opening map; ignore all non-bracket characters.
Early-exit on mismatch; finish by checking the stack is empty.
O(n) time — a count alone fails nested cases like ([)].
Reference solution
def is_balanced(s):
pairs = {")": "(", "]": "[", "}": "{"}
st = []
for ch in s:
if ch in "([{":
st.append(ch)
elif ch in pairs:
if not st or st.pop() != pairs[ch]:
return False
return not stWhat a strong solution covers
- Stack with a closing→opening map.
- Early exit on mismatch.
- Checks the stack is empty at the end.
- O(n) time.
Common mistakes
- only counting brackets (fails
([)]) - popping from an empty stack.