Valid Parentheses

easy

Given a string s containing only the characters '(', ')', '{', '}', '[' and ']', determine whether it is valid.

A string is valid when every open bracket is closed by the same type of bracket, brackets close in the correct order, and every bracket has a matching partner.

Hints

When you see a closing bracket, which open bracket must it match?
It can only match the most recently opened, still-unmatched bracket — that's a stack.
Push openers; on a closer, check the top of the stack is its partner, then pop.

Common doubts

Counts alone can't catch wrong nesting: '([)]' has balanced counts but closes in the wrong order. A stack enforces that a closer matches the nearest open bracket.
A closer when the stack is empty, a closer whose top is the wrong type, or leftover openers at the end (a non-empty stack).
Unmatched openers like in '(((' never trigger a mismatch during the scan; the only place they're caught is the final empty check.

Interview follow-ups

Ignore any character that isn't a bracket — only push/pop on the six bracket symbols.
When a mismatch or empty-pop happens, return the current index; if the scan finishes, the first leftover opener's index is the offending one.

Fun facts

  • Bracket matching is the classic motivating example for stacks and is at the heart of every parser and compiler front-end.
  • The 'delete adjacent pairs until stable' view connects to formal-language reductions and Dyck words in combinatorics.

Asked at

AmazonGoogleMicrosoftMeta
Frequently Sometimes Occasionally
Example 1
Input: s = "()[]{}"
Output: true
Each pair opens and closes correctly in order.
Example 2
Input: s = "([)]"
Output: false
The brackets close in the wrong order: ')' arrives while '[' is still open.
Constraints

- 1 <= s.length <= 10^4 - s consists only of the characters '()[]{}'.

Solve this problem →