/20. Valid Parentheses

20. Valid Parentheses

Easy
Strings43.8% acceptance

Given a string input_str consisting only of the characters (, ), {, }, [ and ], determine whether input_str is a valid sequence of brackets. A valid sequence satisfies the following conditions: 1) Every opening bracket must be closed by the same type of bracket. 2) Brackets must be closed in the correct order. 3) Every closing bracket must have a corresponding opening bracket of the same type.

Example 1

Input: input_str = "{[()]}"

Output: True

Explanation: All brackets are properly nested and matched.

Example 2

Input: input_str = "([{}])"

Output: True

Explanation: All brackets are properly nested and matched.

Example 3

Input: input_str = "([{})]"

Output: False

Explanation: Brackets are not closed in the correct order.

Example 4

Input: input_str = "((((("

Output: False

Explanation: There are unmatched opening brackets.

Example 5

Input: input_str = ""

Output: True

Explanation: Empty string is considered valid.

Constraints

  • 1 <= len(input_str) <= 10_000
  • input_str contains only characters (, ), {, }, [, ]
Python (current runtime)

Case 1

Input: input_str = "{[()]()}"

Expected: True

Case 2

Input: input_str = "{[(])}"

Expected: False

Case 3

Input: input_str = "[({})]"

Expected: True

Case 4

Input: input_str = "{[}"

Expected: False

Case 5

Input: input_str = "(){}[]"

Expected: True