Balanced delimiters
A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.
- Only the characters ( ) [ ] { } matter; everything else is ignored.
- Every opener must have a matching closer of the same kind, in the right order.
- An empty snippet — or one with no brackets at all — is fine.
balanced_delimiters(text: string) → bool
Where you start
def balanced_delimiters(text: str) -> bool:
Worked examples
| Call | Result |
|---|---|
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