Skip to main content
16

Valid Parentheses

Easystackstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:StackRead the beginner guide

Given a string s made only of the characters (, ), {, }, [ and ], return true if the brackets are valid, and false otherwise.

Understand the problem

Think of brackets in code or math: every one you open must be closed properly. Valid means all three of these rules hold:

  1. Same type: a ( must be closed by ), a [ by ], a { by }.
  2. Right order: the bracket you opened most recently must be closed first. Brackets can be nested inside each other, like boxes inside boxes, but they can't cross.
  3. Nothing left over: every opening bracket gets closed, and every closing bracket had an opening one before it.

Example 1

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

[] and {} are each opened and closed inside the outer ( ).

Example 2

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

The [ was opened last, so it must close first. But a ) arrives while [ is still open. The brackets cross, like ( [ ) ].

Example 3

text
Input:  s = "(("
Output: false

Two brackets were opened and never closed.

Example 4

text
Input:  s = "())"
Output: false

The last ) has no opening bracket to match.

Constraints

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

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Push every opening bracket onto a stack, and for every closing bracket, check that the top of the stack is its matching opener and pop it.

    The naive approach (and why it's slow)

    One idea: keep deleting "()", "[]" and "{}" pairs from the string until nothing changes. If the string ends up empty, it was valid.

    text
    "([]{})" → "({})" → "()" → "" ✅

    It works, but each pass scans the whole string and only removes a few pairs, so with deep nesting it takes about n/2 passes of n steps: O(n²).

    The key insight

    Rule 2 says the bracket opened most recently must close first. "Last in, first out" is exactly what a stack does.

    A stack is like a pile of plates:

    • push: put something on top
    • pop: take the top thing off
    • you can only ever see and take the top

    So we keep a stack of the brackets that are still open. The top of the stack is always the one that has to close next.

    Step by step

    s = "([]{})":

    CharOpener or closer?What we doStack afterwards (top on the right)
    (openerpush(
    [openerpush( [
    ]closertop is [, matches ✅ → pop(
    {openerpush( {
    }closertop is {, matches ✅ → pop(
    )closertop is (, matches ✅ → pop(empty)

    The stack is empty at the end, so the answer is true.

    Now s = "([)]":

    CharWhat we doStack afterwards
    (push(
    [push( [
    )top is [, but ) needs ( ❌ → false

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each character is pushed or popped once.
    • Memory: O(n). In the worst case (like "(((((("), every character sits on the stack.

    Common mistakes

    • Popping from an empty stack. A string like ")" starts with a closer. In Python, pop() on an empty list crashes, so check first. (In JavaScript, pop() returns undefined, which simply doesn't match.)
    • Forgetting the final check. "((" never fails a match, but the stack isn't empty at the end, so it's invalid.
    • Just counting brackets. Counting ( vs ) catches "((", but not "([)]", where the counts are fine but the order is wrong.

    Going deeper

    Stacks show up whenever things are nested: matching HTML tags, undo history, evaluating math expressions, and the call stack that runs your functions. When you see "the most recent one" in a problem, think stack.

    Reference solution

    js
    // Each closing bracket -> the opening bracket it must match.
    const openerOf = { ')': '(', ']': '[', '}': '{' }
    
    /**
     * @param {string} s
     * @return {boolean}
     */
    export default function isValid(s) {
      // Brackets that are still open. The top (end of the array) must close next.
      const stack = []
      for (const char of s) {
        if (char in openerOf) {
          // A closer: the most recent open bracket must be its partner.
          // pop() on an empty stack gives undefined, which never matches.
          if (stack.pop() !== openerOf[char]) return false
        } else {
          // An opener: it now waits on top of the stack.
          stack.push(char)
        }
      }
      // Anything still on the stack was never closed.
      return stack.length === 0
    }
    ts
    // Each closing bracket -> the opening bracket it must match.
    const openerOf: Record<string, string> = { ')': '(', ']': '[', '}': '{' }
    
    export default function isValid(s: string): boolean {
      // Brackets that are still open. The top (end of the array) must close next.
      const stack: string[] = []
      for (const char of s) {
        if (char in openerOf) {
          // A closer: the most recent open bracket must be its partner.
          // pop() on an empty stack gives undefined, which never matches.
          if (stack.pop() !== openerOf[char]) return false
        } else {
          // An opener: it now waits on top of the stack.
          stack.push(char)
        }
      }
      // Anything still on the stack was never closed.
      return stack.length === 0
    }
    python
    # Each closing bracket -> the opening bracket it must match.
    OPENER_OF = {")": "(", "]": "[", "}": "{"}
    
    
    def is_valid(s: str) -> bool:
        # Brackets that are still open. The top (end of the list) must close next.
        stack = []
        for char in s:
            if char in OPENER_OF:
                # A closer: the most recent open bracket must be its partner.
                # Check for an empty stack first: pop() on an empty list crashes.
                if not stack or stack.pop() != OPENER_OF[char]:
                    return False
            else:
                # An opener: it now waits on top of the stack.
                stack.append(char)
        # Anything still on the stack was never closed.
        return not stack