Skip to content
Problem 20 · LeetCode 20(opens in a new tab)

Valid Parentheses

EasyStacks

You get a string s made only of bracket characters: (, ), [, ], { and }. Return true if the brackets are properly matched, and false if they are not.

Matched means three things. Each opener is closed by a bracket of its own kind. Brackets close in reverse order of opening, so the most recent open bracket must close first. And no closer appears without an open bracket waiting for it.

Example 1

Input:  s = "{[]()}"
Output: true
Why:    [] and () close inside {}, each in order
2 more examples and the constraints

Example 2

Input:  s = "{(})"
Output: false
Why:    } arrives while ( is still open

Example 3

Input:  s = "(("
Output: false
Why:    neither ( is ever closed

Constraints

  • 1 ≤ length of s ≤ 10,000
  • s contains only the six characters ( ) [ ] { }

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Remove adjacent pairsO(n²)
  2. Stack of expected closersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 brackets, deeply nestedVerdict
Remove adjacent pairsO(n²)
Intuitive, but too slow when nested deep
Stack of expected closersO(n)
Best; one pass, the standard answer

n = length of s.

Edge cases to test

  • Starts with a closer. ")" or "])}" must return false at once. Check the stack is not empty before popping.
  • Openers left over. "((" never fails a match, but the stack is not empty at the end, so the answer is false.
  • Counts match, order does not. "(()))(" has three of each, yet a ) arrives with nothing open. Counting is not enough.
  • Right kinds, wrong order. "{(})" closes } while ( is still on top, so it is false.

Common mistakes

  • Only counting openers and closers, which passes "(()))(" and "{(})".
  • Popping or peeking an empty stack when the string starts with a closer.
  • Returning true after the loop without checking the stack is empty.

How to talk through it

  1. 1Clarify. Only the six bracket characters? Can the string be empty? Is a lone closer simply invalid?
  2. 2Give the simple idea. Keep deleting adjacent pairs; say it works but can need n / 2 rounds, so O(n²).
  3. 3Name the structure. The last bracket opened is the first that must close: that is a stack.
  4. 4Code the one pass. Push the needed closer for each opener, compare each closer with the top, and check the stack is empty at the end.
  5. 5Test out loud. Run a lone closer, leftover openers and "{(})" before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?