Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python bracket stack: reject mismatches at the first invalid close

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

A bracket validator uses a stack of expected closing tokens to check properly nested bracket sequences.

Download Python source kit

Operation contract

The import expression parser pushes the matching closer for every opener. A closer must match the top expectation; a mismatched closer or a leftover opener makes the expression invalid. The fixture accepts only bracket characters and caps input length, so ordinary text cannot be silently ignored as though it were parsed.

Failure and ownership boundary

This is bracket validation, not a Python parser. Quoted strings, comments and expression semantics require a grammar that knows whether a bracket is actually syntax. Python strings and bytes: reject decoding errors before parsing records defines an earlier layer, while Java stack algorithm: validate nested delimiters checks the same nesting invariant.

Working program

python
def balanced_brackets(text):
    if len(text) > 4096:
        raise ValueError("expression too long")
    closing = {"(": ")", "[": "]", "{": "}"}
    expected = []
    for token in text:
        if token in closing:
            expected.append(closing[token])
        elif token in ")]}":
            if not expected or expected.pop() != token:
                return False
        else:
            raise ValueError("brackets only")
    return not expected

print(balanced_brackets("{[()]}"))
print(balanced_brackets("([)]"))
print(balanced_brackets("(("))

Output

Output
True
False
False

Costs and limits

For n bracket tokens the scan is O(n) time and worst-case O(n) stack storage. Early mismatch can stop before consuming every token.

Common Mistakes

  • Validate the top expectation rather than only counting tokens.
  • A bracket checker is not a source-language parser.

Connected lessons

Python lists: slicing copies the outer sequence, not nested objects, Python strings and bytes: reject decoding errors before parsing records, Java stack algorithm: validate nested delimiters.

python
bracket-stack
Storage details