PrepStack · Markdown HTML

Balanced-delimiter stack

Stack and monotone deque · HTML

Formal shape

Scan tokens; push every opener. A closer requires a nonempty stack with top=matching_open(closer), then pops it. The input is balanced exactly when the stack is empty at the end.

Recognition signals

False friends

SignalWhy it is different
One delimiter type and count onlyA balance counter may suffice, but multiple types require a stack to reject crossings.
Can delete arbitrarily to become validMinimum deletion or all repair plans need more than one validation pass.

Core invariant

After a prefix, the stack contains exactly its unmatched openers in occurrence order; the top is the only opener the next closer may legally match.

State, transition, and processing order

ItemDefinition
StateStack of opener symbols or indexes, closer-to-opener map, and optional maximum depth or error position.
TransitionPush an opener; for a closer, verify nonempty and matching type, then pop, otherwise fail or record repair information.
Frontier / orderAll unfinished nesting levels, with the newest opener at top and therefore due to close first.

Python skeleton

def delimiters_balanced(text):
    match = {')': '(', ']': '[', '}': '{'}
    opening = set(match.values())
    stack = []
    for ch in text:
        if ch in opening:
            stack.append(ch)
        elif ch in match:
            if not stack or stack[-1] != match[ch]:
                return False
            stack.pop()
    return not stack

Correctness sketch

  1. Every opener is pushed and removed only by its correct closer, so all produced pair types match.
  2. LIFO enforces inner-before-outer closure and rules out crossing pairs.
  3. A mismatching closer cannot legally skip the top; an empty final stack means no opener remains unmatched.

Complexity

TimeSpaceParameters
O(n)O(d)n is input length and d maximum nesting depth, with d up to n.

Edge cases

Error patterns

PatternWhy it fails / fix
Counting opens and closes only([)] has balanced counts but invalid nesting.
Reading stack[-1] before checking emptinessAn extra closer causes an exception.
Skipping the final empty checkA prefix missing closers is incorrectly accepted.

Selection and exclusion rules

RelationTemplateBoundary
repair/pairing extensionInterval dynamic programmingInsertions or deletions are allowed and minimum repair cost is required.
specializationStack-based state simulationA general frame collapses to one opener or index.

Original micro-example

PartDetail
ResultThe stack ends empty, so nesting is valid.
SetupToken stream { [ ] ( ) }.
TracePush { and [; ] pops [; push (; ) pops (; } pops {.

Recall prompts

My notes