Balanced Delimiter Validation with a Stack
Stacks & QueuesAuto-graded · 23 test casesLast updated
Decide whether a bracket-only string is properly nested and matched, using a LIFO stack of pending openers.
You are given a string brackets containing only the six delimiter characters (, ), [, ], {, }.
Decide whether the string is well formed. A string is well formed exactly when all three conditions hold:
- Each opening delimiter is eventually closed by a delimiter of the same kind.
- Delimiters close in properly nested order — the most recently opened delimiter must be the next one closed.
- A closing delimiter never appears without a matching opener of the same kind still waiting to be closed.
Return True if the string is well formed, otherwise return False.
Constraints
1 <= len(brackets) <= 10^4bracketsconsists only of the characters(,),[,],{,}.
Examples
Example 1
Input: is_well_formed('()[]{}')
Output: True
Example 2
Input: is_well_formed('([)]')
Output: False
Example 3
Input: is_well_formed('{[]}')
Output: True
Hints
Hint 1
Nesting is last-in-first-out, so track pending openers in a stack.
Hint 2
When a closer arrives, the thing it must match is exactly the most recent unmatched opener.
Hint 3
Three failure signals: a closer with an empty stack, a closer that disagrees with the stack top, and openers left over at the end.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Balance checking is inherently last-in-first-out: the delimiter opened most recently must be the one closed next. So keep a stack of openers still waiting for a partner and scan the string left to right.
- On an opening delimiter, push it onto the stack.
- On a closing delimiter, it must match whatever is on top of the stack. If the stack is empty there is no partner, so return
False. Otherwise pop the top and compare; a mismatch means the wrong kind or the wrong order, so returnFalse. - After the scan finishes, only an empty stack means every opener was closed; return whether the stack is empty.
A lookup table mapping each closer to its matching opener makes the comparison a single O(1) dictionary access.
Why It Is Correct
Invariant: after reading a prefix, the stack holds exactly the unmatched openers of that prefix, ordered outermost to innermost with the innermost on top. Any valid closure must pair a closer with the innermost still-open delimiter — precisely the stack top. A mismatch (a different kind, or a crossing like "([)]") violates nesting, and a closer arriving at an empty stack has no partner. If the scan finishes without failing, every closer matched, and a non-empty stack would mean an unclosed opener. The invariant guarantees the returned answer matches the definition.
Complexity
- Time: O(n) — each character is processed once with O(1) stack and dictionary operations.
- Space: O(n) worst case for the stack (for example, all openers); the size equals the maximum nesting depth, which can stay O(1) for inputs like
"()()()".
Reference Solution
def is_well_formed(brackets: str) -> bool:
opener_for = {')': '(', ']': '[', '}': '{'}
pending = []
for ch in brackets:
if ch in '([{':
pending.append(ch)
elif not pending or pending.pop() != opener_for[ch]:
return False
return not pending