Start learning free

LESSON 467 OF 677 · STACK

Valid Parentheses

Practice O(n)

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

Properly matched means:

  1. Every opening bracket is closed later by a bracket of its own kind.
  2. A bracket opened later is closed first. Pairs sit inside each other and never cross.
  3. Every closing bracket closes a bracket opened before it.

Example 1:

Input: input = "{()[]}"
Output: true
Explanation: () and [] both sit inside the {} pair.

Example 2:

Input: input = "{[(])}"
Output: false
Explanation: The ] comes while the ( is still open.
The ( and [ pairs cross.

Example 3:

Input: input = "(()"
Output: false
Explanation: One ( is never closed.

Constraints:

  • input has 1 to 7,000 characters.
  • Every character is one of the six brackets.

Note:

Your algorithm should run in O(n) time and use O(n) extra space.


STEP 1 OF 11
    Ctrl + Enter to check