Determine whether a bracket string has matching types, correct nesting, and no unmatched brackets.
Problem
Input. A string text containing only the six bracket characters ()[]{}.
Output. Return True if every bracket is correctly matched and nested; otherwise return False.
Rules. Each opener needs a later closer of the same type. Pairs may be nested or adjacent, but may not cross. Equal counts alone are insufficient. Leave the string unchanged. Empty text is valid; other characters require the filtering variant below.
Example. "([{}])" and "()[]" return True.
For "([)]", return False because the pairs cross; a lone "(" also returns False.
Picture: Close From Newest to Oldest
Problem trace
Separate nesting failure: the closer cannot skip the top unmatched opener
Reference drawing
Problem trace
Each closing bracket must match the most recent unmatched opening bracket
Execution trace
- top
- (0, 0)
- input
- ([{}])
- layout
- bottom to top
- current
- before index 0→index 0: (
- action
- initialize→push (
- column 0 / row 0
- empty→(
- top
- (0, 0)→(1, 0)
- current
- index 0: (→index 1: [
- action
- push (→push [
- top
- (1, 0)→(2, 0)
- current
- index 1: [→index 2: {
- action
- push [→push {
- top
- (2, 0)→(1, 0)
- current
- index 2: {→index 3: }
- action
- push {→pop {; expected {
- top
- (1, 0)→(0, 0)
- current
- index 3: }→index 4: ]
- action
- pop {; expected {→pop [; expected [
- current
- index 4: ]→index 5: )
- action
- pop [; expected [→pop (; expected (
- result
- not shown→true
- Recognize it
- Use this pattern when nested delimiters must close in reverse opening order and each closer must validate the most recent unfinished opener.
- Keep true
- After each processed character, the stack contains exactly the unmatched opening brackets from the processed prefix, ordered oldest at the bottom and newest at the top.
- Reuse it
- For tags, expression delimiters, and nested scopes, store only unfinished openers and let each closer inspect the newest one; an empty stack at the end proves completion.
| Read | Stack, oldest to newest | Action |
|---|---|---|
( | ( | Push |
[ | (, [ | Push |
{ | (, [, { | Push |
} | (, [ | Match and pop { |
] | ( | Match and pop [ |
) | Empty | Match and pop ( |
After every accepted prefix, opening contains exactly the unmatched openers in their original order.
Its top is the only opener the next closer may finish; searching deeper would permit crossing pairs.
Reject a closer with no opener or the wrong top. Final emptiness proves completion only after those checks passed.
Code
def valid_parentheses(text: str) -> bool:
opening: list[str] = []
matching = {")": "(", "]": "[", "}": "{"}
for char in text:
if char not in matching:
opening.append(char)
elif not opening or opening.pop() != matching[char]:
return False
return not opening
Time is with amortized constant-time list pushes and pops. Space is for maximum nesting depth, in the worst case. The original pushes every noncloser; it does not ignore ordinary text.
Change 1: Ignore Nonbracket Text
New task. Ordinary characters are irrelevant; bracket nesting still matters.
Picture and change. Push only explicit openers. Ignore other nonclosers.
Code.
def balanced_brackets_in_text(text):
stack = []
matching = {")": "(", "]": "[", "}": "{"}
for character in text:
if character in "([{":
stack.append(character)
elif character in matching:
if not stack or stack.pop() != matching[character]:
return False
return not stack
Check. "a(b[c])" passes; "a([)]" fails. Quotes and comments have no special treatment.
Use when. The declared input grammar makes nonbrackets irrelevant, not for parsing a programming language.
Change 2: Permit Only Round Parentheses
New task. The alphabet is only (); reject every other character.
Picture and change. One type needs only a depth counter. Every prefix must stay nonnegative; final depth must be zero.
Code.
def balanced_round(text):
depth = 0
for character in text:
if character == "(":
depth += 1
elif character == ")":
depth -= 1
if depth < 0:
return False
else:
return False
return depth == 0
Check. "(())()" passes; ")(" fails despite final balance zero. This variant uses constant auxiliary space.
Use when. Removing type distinctions makes ordered obligations reducible to one count.
Failure: Counts Without Nesting
"([)]" fails as soon as ) meets [. Also reject early ")" and unfinished "(".
Transfer Check
Why does a queue fail?
Reasoned Answer
A closer finishes the most recently opened unfinished scope, not the oldest. First-in-first-out order contradicts nesting.
Separate Matching From Completion
The short-circuit not opening or ... prevents popping an empty stack.
A nonempty stack after the scan means unfinished work remains, even if no mismatch occurred.
An empty final stack is not enough if earlier closers were never validated.
For mixed brackets, depth alone cannot distinguish ([)] from ([]).
The ordered type sequence is necessary state. For one type, the counter retains everything needed and removes unnecessary type storage.
The text-ignoring variant still treats bracket characters inside quoted strings or comments as delimiters. It is not an HTML/XML parser, a Python parser, or a tokenizer that recognizes escapes. Use a grammar-aware parser when those constructs affect whether a bracket is active.