Skip to problem
←

Valid Parentheses

Easy 0 attempts
Daily

You're given a string made up exclusively of the bracket characters '(', ')', '{', '}', '[', and ']'. Figure out whether the brackets in it are properly balanced.

The string counts as valid when every opening bracket is eventually closed by the matching bracket type, and the closures happen in the right nested order. An empty string is trivially valid.

Function contract

Implement isValid(s), where s is a string containing only bracket characters.

Output: A boolean: true if all brackets match in the correct nested order, otherwise false.

Example 1

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

Example 2

Input
s = "([)]"
Output
false

Explanation: The closing parenthesis appears before the square bracket has closed, so the nesting is invalid.

Visual Aid
Matching brackets must nest
([])([)]Nested: validCrossing: invalid

Each closing bracket must match the most recent opening bracket that is still unmatched.

Constraints
  • 0 <= s.length <= 10^4
  • s consists of '()[]{}' only.

Use a stack. Push every opening bracket. When a closing bracket appears, check that the stack is non-empty and the top matches. If the stack is empty at the end, all brackets were properly matched.

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

  for (const ch of s) {
    if (ch === '(' || ch === '{' || ch === '[') {
      stack.push(ch);
    } else {
      if (stack.length === 0 || stack[stack.length - 1] !== pairs[ch]) {
        return false;
      }
      stack.pop();
    }
  }

  return stack.length === 0;
}

Time: O(n) — single pass through the string. Space: O(n) — the stack can hold n elements when every character is an opening bracket.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript