Skip to content
DSA Patterns
Menu
Language
Stack ParsingLC #201 of 6Next →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

Valid Parentheses

Problem (restated)

Given a string of brackets, determine if it is valid (correct nesting and order).

Intuition

Push openers; on closer, top must match.

Approaches

Stack matching

Unverified
Time O(n)Space O(n)

Idea. Stack + map of closing→opening.

Walkthrough. “()[]” true; “(]” false.

Trade-offs. Stack is canonical; counter only works for one type.

Solution
export function isValid(s: string): boolean {
  const st: string[] = [];
  const pair: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
  for (const ch of s) {
    if (ch === '(' || ch === '[' || ch === '{') st.push(ch);
    else {
      if (!st.length || st.pop() !== pair[ch]) return false;
    }
  }
  return st.length === 0;
}
export function isValid(s: string): boolean {
  const st: string[] = [];
  const pair: Record<string, string> = { ')': '(', ']': '[', '}': '{' };
  for (const ch of s) {
    if (ch === '(' || ch === '[' || ch === '{') st.push(ch);
    else {
      if (!st.length || st.pop() !== pair[ch]) return false;
    }
  }
  return st.length === 0;
}

Template connection

Matching shape: push each opener, and a closer pops the opener it maps to. The string is valid when every pop finds that opener and the stack is empty at the end.

Reflection

  • On an opener, push the closer you expect. A closer that is not the top, or an empty stack, is false.
  • ([)] catches a bad order. (() catches a missing close. Is the stack empty at the end?
  • The empty string is true. One character is false.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 6
1/6

Matching brackets. Stack holds unmatched openers; a closer must pair with the top.

(
0
[
1
]
2
)
3
stack
∅
Key:CurrentActive rangeMatchSettled