Valid Parentheses

Easy

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if open brackets are closed by the same type and in the correct order.

Examples

InputOutput
s = "()"true
s = "([)]"false

Python Solution

def is_valid(s: str) -> bool:
    stack = []
    pairs = {")": "(", "}": "{", "]": "["}
    for c in s:
        if c in pairs:
            if not stack or stack[-1] != pairs[c]:
                return False
            stack.pop()
        else:
            stack.append(c)
    return len(stack) == 0

JavaScript Solution

function isValid(s) {
  const stack = [];
  const pairs = { ")": "(", "}": "{", "]": "[" };
  for (const c of s) {
    if (pairs[c]) {
      if (!stack.length || stack.pop() !== pairs[c]) return false;
    } else stack.push(c);
  }
  return stack.length === 0;
}

Step-by-Step Explanation

  1. Use a stack to track opening brackets.
  2. For closing brackets, check if the top of the stack matches.
  3. If not, or stack is empty, return false.
  4. At the end, the stack must be empty.

Complexity Analysis

TimeO(n)
SpaceO(n)

Tags

StringStack

Related Problems

Related Tools

All Problems