Practice · Stack · 1 of 3

Valid Brackets

A string s contains only the six characters (, ), [, ], { and }.

Return true if the brackets are balanced: every opening bracket is closed by a bracket of the same kind, closings happen in the reverse order of openings (so ([)] is not balanced), and no closing bracket appears without an opening one before it. Return false otherwise.

Example 1

Input
s = "{[]()}"
Output
true
[] and () close inside the braces, and the braces close last.

Example 2

Input
s = "([)]"
Output
false
) arrives while [ is the most recent open bracket.

Example 3

Input
s = "(("
Output
false
Two brackets are never closed.

Constraints

  • s holds 1 to 10⁴ characters.
  • Every character is one of ()[]{}.
Brush up firstStack visualiser