Skip to the code
cf.
+10 XP

#249 Check Bracket Balance in a Template

easy

A template editor warns you when the brackets in a snippet don't line up. A snippet is balanced when every (, [, and { is closed later by the matching ), ], or }, and pairs never cross: ([]) is fine but ([)] is not.

Write isBalanced(snippet) that returns true if the brackets in snippet are balanced and false otherwise. Every other character, such as letters, spaces, and dots, is ignored. A snippet with no brackets is balanced.

Example 1

Input: snippet = "if (items[0]) { render(); }"
Output: true

Every bracket closes in the right order.

Example 2

Input: snippet = "{{ user.name }"
Output: false

One { is never closed.

Constraints

  • 0 <= snippet.length <= 10^4
  • snippet has printable ASCII characters.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).