BeginnerStacks

Balanced brackets

Task

Write is_balanced(s) that returns True if every ( [ { in the string is closed by the matching bracket in the right order, and False otherwise. Ignore all other characters.

Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.

Tests
CallExpected
is_balanced('(a[b]{c})')True
is_balanced('([)]')False
is_balanced('((')False
is_balanced('')True
is_balanced('}{')False
is_balanced('f(x[0]) + {k: v}')True
Show solution
Python
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

A stack remembers the order brackets were opened, so each closing bracket can be checked against the most recent unclosed one.

Revise in the Python guide, or test yourself with the Python practice sets.