LearnCoding

Balanced brackets

Warm-upStack, Strings

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
True

Solve it in your own editor; nothing on this page runs code.

Hints

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 st

What 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.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.