Skip to content
ΣDSA Patterns
Menu
Language

Stack Parsing

Guide 1 of 6 · Path 1 of 6

PreviousNext

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

Tested only
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

Stack parsing matching.

Reflection