Medium Stack Matching Stacks & Queues
In plain English: Check if every opening bracket has a matching closing bracket in the correct order.
A stack naturally models nesting: the most recent opening bracket must match the next closing bracket — LIFO order.
Prompt
Check if a string of brackets is balanced: ()[]{}
Try to write it from scratch before scrolling down.
Solution
def is_balanced(s):
stack = []
pairs = {')':'(', ']':'[', '}':'{'}
for c in s:
if c in '([{':
stack.append(c)
# LIFO matches innermost first
elif c in pairs:
if not stack or stack.pop() != pairs[c]:
return False
return len(stack) == 0
# Test: is_balanced("{[()]}") == True
# Test: is_balanced("{[(])}") == False