Valid Parentheses

Easy

Topics
StringStack

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

Example 1

(0)1[2]3{4}5
Every bracket closes the most recently opened one of the same kind, so the answer is true. Counting brackets is not enough — ([)] has balanced counts and is still invalid, which is why the order a stack enforces matters.
Cells are the characters of the string; the small numbers underneath are indices.
Input:  s = "()[]{}"
Output: true

Example 2

(0[1)2]3
The shaded bracket is the failure: either it closes the wrong kind, or it is never closed at all. Both are caught by a stack — push openers, and on a closer check the top matches before popping.
Input:  s = "([)]"
Output: false

Constraints

  • 1 <= s.length <= 10^4
  • s consists of brackets only.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Brackets must close in the reverse order they open: the most recently opened bracket must be the first one closed. "Last opened, first closed" is the definition of a stack (LIFO).

So we push every opening bracket and, on every closing bracket, verify it matches the bracket on top of the stack.

Approach

  1. Maintain a stack of unmatched opening brackets.
  2. For an opening bracket, push it.
  3. For a closing bracket, the top of the stack must be its matching open — if the stack is empty or the top is wrong, the string is invalid.
  4. At the end, the stack must be empty; leftover opens mean unclosed brackets.

Walkthrough

s = "([])"

(  push       stack=[ (
[  push       stack=[ ( [
]  top=[ ok   stack=[ (
)  top=( ok   stack=[]
end: stack empty -> valid

Complexity

  • Time — O(n): each character is pushed and popped at most once.
  • Space — O(n): a string of all opening brackets fills the stack.

Common Pitfalls

  • Forgetting the final empty-stack check accepts strings like "(".
  • A closing bracket when the stack is empty (e.g. ")") must return false, not crash.

Full Solution — all languages

class Solution:
    def isValid(self, s):
        pairs = {')': '(', ']': '[', '}': '{'}
        stack = []
        for c in s:
            if c in pairs:
                if not stack or stack.pop() != pairs[c]:
                    return False
            else:
                stack.append(c)
        return not stack
SensAI
Beta
Tap the mic to stop voice mode