Skip to content
mlmentorship

Valid Parentheses

Check whether all brackets close in the correct order.

Published · 9 min read ·Core ·Foundation

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Valid Parentheses

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

A closing bracket is valid only when it removes its matching newest unmatched opening bracket.

Problem trace

Each closing bracket must match the most recent unmatched opening bracket

Input and goalCheck whether all brackets close in the correct order.
Initialize an empty stackBefore scanning ([{}]), there is no unmatched opening bracket.
emptytop
input([{}])layoutbottom to topcurrentbefore index 0actioninitialize
top
(0, 0)
input
([{}])
layout
bottom to top

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.
Before scanning ([{}]), there is no unmatched opening bracket. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can equal counts of each bracket type still fail for ([)]? Why must the stack also be empty after the scan?
Full interview answer 9 min read
Reading depth

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

Worked example: a closing bracket must match the most recent openerFor ([)], the ) encounters [ on top. A matching ( deeper in the stack does not make the sequence valid.A closer tests the top opener, not amatching deeper oneInput so far: ([ ; incoming ))([topdeeperThe required round opener is deeper.The actual top is square, so reject.A matching opener somewhere in thestack cannot bypass last-in-first-outorder.
Read it this way: For ([)], the ) encounters [ on top. A matching ( deeper in the stack does not make the sequence valid. Can the closer skip the top square opener to use the round opener deeper in the stack?
Reference drawing

Problem trace

Each closing bracket must match the most recent unmatched opening bracket

Worked example: a closing bracket must match the most recent openerFor ([)], the ) encounters [ on top. A matching ( deeper in the stack does not make the sequence valid.A closer tests the top opener, not amatching deeper oneInput so far: ([ ; incoming ))([topdeeperThe required round opener is deeper.The actual top is square, so reject.A matching opener somewhere in thestack cannot bypass last-in-first-outorder.
Execution trace
Input and goalCheck whether all brackets close in the correct order.
Initialize an empty stackBefore scanning ([{}]), there is no unmatched opening bracket.
emptytop
input([{}])layoutbottom to topcurrentbefore index 0actioninitialize
top
(0, 0)
input
([{}])
layout
bottom to top

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.
Before scanning ([{}]), there is no unmatched opening bracket. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can equal counts of each bracket type still fail for ([)]? Why must the stack also be empty after the scan?
Read it this way: For ([)], the ) encounters [ on top. A matching ( deeper in the stack does not make the sequence valid. Can the closer skip the top square opener to use the round opener deeper in the stack?
ReadStack, oldest to newestAction
((Push
[(, [Push
{(, [, {Push
}(, [Match and pop {
](Match and pop [
)EmptyMatch 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.