# The Syntax Sentinel

> Brackets opened and closed. The nesting might be off.

Canonical URL: <https://datadriven.io/problems/the_syntax_sentinel>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a string, return True if all bracket pairs (), [], {} are balanced and properly nested. Non-bracket characters are ignored.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests the **stack data structure** applied to bracket matching, a classic parsing problem. It probes whether a candidate understands LIFO ordering and can map opening brackets to their closing counterparts.

---

### Break down the requirements

#### Step 1: Push opening brackets onto a stack

When you encounter `(`, `[`, or `{`, push it onto the stack.

#### Step 2: Pop and match closing brackets

When you encounter `)`, `]`, or `}`, pop the stack and verify it matches the expected opening bracket.

#### Step 3: Ignore non-bracket characters

The string may contain letters, digits, and other characters that should be skipped.

#### Step 4: Verify the stack is empty at the end

Unmatched opening brackets remain on the stack, indicating imbalance.

---

### The solution

**Stack-based bracket matching**

```python
def is_balanced(s: str) -> bool:
    stack = []
    matching = {')': '(', ']': '[', '}': '{'}
    for ch in s:
        if ch in '([{':
            stack.append(ch)
        elif ch in ')]}':
            if not stack or stack[-1] != matching[ch]:
                return False
            stack.pop()
    result = len(stack) == 0
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) for a single pass through the string.
> 
> **Space:** O(n) in the worst case where every character is an opening bracket.

> **Interviewers Watch For**
>
> The `not stack` check before accessing `stack[-1]` prevents IndexError on unmatched closing brackets. This defensive check is the mark of a careful implementer.

> **Common Pitfall**
>
> Using a counter instead of a stack. Counters can track parentheses but cannot verify that bracket types are correctly nested. `([)]` would pass a counter check but fail a stack check.

---

## Common follow-up questions

- What if you needed to return the position of the first mismatch? _(Tests modifying the function to track indices alongside bracket characters.)_
- How would you handle angle brackets that also appear as comparison operators? _(Tests context-aware parsing where `<` and `>` have dual meanings.)_
- What if the string could contain escaped brackets like `\(`? _(Tests adding a lookahead or escape-state tracking to the parser.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_syntax_sentinel)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.