Drill

ProblemsPython › patterns

Balanced delimiters

easypatternsStacksStringsPython

A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.

balanced_delimiters(text: string) → bool

Solve it in the editor →

Where you start

def balanced_delimiters(text: str) -> bool:
    

Worked examples

CallResult
balanced_delimiters("()")True
balanced_delimiters("([])")True
balanced_delimiters("(]")False
balanced_delimiters("[(])")False

Hint

Push each opener, and when a closer arrives the top of the stack must be its matching opener.

Reference solution in Python
def balanced_delimiters(text: str) -> bool:
    expect = []
    for ch in text:
        if ch == '(':
            expect.append(')')
        elif ch == '[':
            expect.append(']')
        elif ch == '{':
            expect.append('}')
        elif ch in ')]}':
            if not expect or expect.pop() != ch:
                return False
    return len(expect) == 0

The same problem in another language

More patterns problems in Python