Valid Parentheses

25 min · isValid()

One misplaced bracket can change what an entire program means. Here, every character is a bracket, so every one has to land in exactly the right place.

You're given a string s containing only (, ), [, ], {, and }. An opener is a left bracket such as (; a closer is its right-bracket partner, such as ).

Return true when every opener is closed by the same bracket type and the pairs close in the correct order. Return false otherwise.

A few ground rules:

  • A closer must match the most recent opener that hasn't been closed yet.
  • No opener may be left behind, and no closer may arrive without a matching opener.
  • The input contains brackets only — there are no letters or spaces to skip.

Constraints

  • 1 <= s.length <= 100_000
  • s consists only of ()[]{}.

Hints

Try removing finished pairs

Repeatedly erase every adjacent (), [], and {}. A valid string eventually disappears. What does that cost when 50,000 pairs are nested inside one another?

Remember unfinished work

A stack is a collection where the last item added is the first one removed. Store each opener as you scan from left to right, then compare each closer with the opener on top.

Store the answer you expect

When you see (, push ) rather than (. Then every closer has one job: equal the top of the stack. At the end, the stack must also be empty.

Follow-up

Could you reject a bad string the moment it becomes impossible, while reading its characters only once?

Visible cases

Examples

Example 1

ready
Input
s = "()[]{}"
Expected
true
Why
each pair closes cleanly before the next begins

Example 2

ready
Input
s = "(]"
Expected
false
Why
the square closer cannot close a round opener

Example 3

ready
Input
s = "([)]"
Expected
false
Why
the pairs have matching types but close in the wrong order

Interview signal

Asked at

AmazonGoogleMicrosoftMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite