Valid Parentheses

Difficulty: Easy

You're given a string of the bracket characters (, ), [, ], {, and }. Return whether the brackets are balanced.

Balanced means every opening bracket has a closing bracket of the same type, and they close in the right order: the most recently opened bracket must close first.

Examples

Input: s = "()[]{}"
Output: true

Each pair opens and closes cleanly, and none of the pairs overlap improperly.

Input: s = "(]"
Output: false

The opening '(' ends up closed by ']', which is the wrong type of bracket.

Input: s = "([)]"
Output: false

'(' opens, then '[' opens — but ')' shows up before '[' has been closed, closing things out of order.

Constraints

  • 1 <= s.length <= 10^4

  • s consists only of the characters '(', ')', '[', ']', '{', and '}'.

Approach

A closing bracket must match the most recently opened bracket that is still open. That's last-in, first-out, which is what a stack is for.

Walk through the string:

  • Opening bracket: push it.
  • Closing bracket: pop the top. If it's the wrong type, or the stack is empty, the string is invalid.

At the end, the string is valid only if the stack is empty. Anything left was opened but never closed.

Solutions

Brute Force — Repeatedly Remove Matched Pairs

Keep removing adjacent matched pairs like "()", "[]", or "{}" from the string. If it shrinks to empty, it was valid. This works, but it re-scans the string over and over.

function isValid(s) {
  let previous;
  do {
    previous = s;
    s = s.replace("()", "").replace("[]", "").replace("{}", "");
  } while (s !== previous);

  return s.length === 0;
}

Time: O(n²) · Space: O(n)

Optimal — Stack

Push opening brackets onto a stack. For each closing bracket, pop the stack and check it's the matching opening bracket. If it isn't, or the stack is empty, the string is invalid.

function isValid(s) {
  const stack = [];
  const pairs = { ")": "(", "]": "[", "}": "{" };

  for (const char of s) {
    if (char === "(" || char === "[" || char === "{") {
      stack.push(char);
    } else {
      if (stack.pop() !== pairs[char]) {
        return false;
      }
    }
  }

  return stack.length === 0;
}

Time: O(n) · Space: O(n)