Balanced Brackets

EasyStack≈ 15 min

Given a string made only of the brackets (, ), [, ], { and }, return whether it is balanced:

  • every opening bracket is closed by a bracket of the same kind, and
  • brackets close in the reverse order they were opened.

Examples

text
"[]"       →  true
"{()[]}"   →  true
"(}"       →  false
"{[}]"     →  false
"([{}])"   →  true

"{[}]" is not balanced: the } arrives while [ is the bracket still open.

Constraints

  • Between 0 and 100,000 characters, all of them brackets.
  • Aim for O(n): one pass over the text.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 5 visible cases here, in your browser. Submit runs all 9 on the judge, 4 of them hidden, and measures how your solution scales.