Back to blog

March 28, 2026 · 5 min read

Valid Parentheses: Why Stack Is the Cleanest Fit

How I approach bracket-matching problems with a stack, and the exact checks that avoid false positives.

AlgorithmsData StructuresLeetCode

Complexity

Time: O(n)

Space: O(n)

Problem in My Words

Verify every opening bracket is closed in the correct order and with the correct bracket type.

Approach

Push opening brackets to stack. On closing bracket, compare with stack top using a map. If mismatch or empty stack, invalid.

Key Points

  • Early return on mismatch improves readability.
  • Map-based matching avoids long condition chains.
  • Stack must be empty at the end.

Implementation

function isValid(s: string): boolean {
  const pairs: Record<string, string> = {")": "(", "]": "[", "}": "{"};
  const stack: string[] = [];

  for (const ch of s) {
    if (ch === "(" || ch === "[" || ch === "{") {
      stack.push(ch);
      continue;
    }

    const top = stack.length ? stack.pop() : undefined;
    if (top !== pairs[ch]) {
      return false;
    }
  }

  return stack.length === 0;
}