Skip to content
LEETFLIX

Valid Parentheses

Solve on LeetCode

The canonical stack problem. If you can explain LIFO with this, you understand stacks.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

Given a string s containing just the characters (, ), {, }, [ and ], determine if the input string is valid.

An input string is valid if:

  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
  3. Every close bracket has a corresponding open bracket of the same type.

Constraints

  • —1 <= s.length <= 10^4
  • —s consists of parentheses only ()[]{}.

Examples

Input

s =
"()"

Output

true

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Stack of open brackets

Push openers; on a closer, the top of the stack must be its matching opener.

Keep a stack of the brackets that are currently open. A closing bracket is only legal if the stack's top is its partner — pop it. Anything else is an immediate false. At the end, the stack must be empty.

A small pairs map (close → open) keeps the code free of a six-way if/elif chain and doubles as the “is this a closing bracket?” test.

Algorithm

  1. Build pairs = { ')': '(', ']': '[', '}': '{' } and an empty stack.
  2. For each character: if it's a closer, the stack must be non-empty and its top must equal pairs[ch] — otherwise return false. Pop.
  3. If it's an opener, push it.
  4. Return true iff the stack is empty at the end.
Time
O(n)
Space
O(n)

Worst case (all openers) the stack holds every character.

Solution.py
class Solution:    def isValid(self, s: str) -> bool:        pairs = {")": "(", "]": "[", "}": "{"}        stack: list[str] = []        for ch in s:            if ch in pairs:  # closing bracket                if not stack or stack[-1] != pairs[ch]:                    return False                stack.pop()            else:  # opening bracket                stack.append(ch)        return not stack
Watch this run

03

Interactive walkthrough

Playing “Stack of open brackets”. Edit the input, hit Run, then scrub.

Approach: Stack of open brackets

Loading animation…

Up next