---
title: Balanced brackets
url: https://gurkanozkan.ai/learn/coding/mle-balanced-brackets-32/
markdown: https://gurkanozkan.ai/learn/coding/mle-balanced-brackets-32.md
kind: coding
difficulty: Warm-up
topics:
  - Stack
  - Strings
json: https://gurkanozkan.ai/api/learn/coding/mle-balanced-brackets-32.json
robots: noindex
---

# Balanced brackets

Return `True` if every bracket among `()[]{}` in `s` is properly matched and nested. Ignore all other characters.

## Signature

```python
def is_balanced(s: str) -> bool: ...
```

## Examples

Each call and the value it should give.

```python
>>> is_balanced('([]{})') == True
True

>>> is_balanced('([)]') == False
True
```

## Hints

1. Stack with a closing->opening map; ignore all non-bracket characters.
2. Early-exit on mismatch; finish by checking the stack is empty.
3. O(n) time — a count alone fails nested cases like ([)].

## Reference solution

```python
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.*
