Bracket Inspector
Write the check behind every code editor's bracket matching: three bracket types, any nesting depth, other characters ignored.
Statement
Story
Your editor plugin must decide, before it reformats a file, whether the brackets in a snippet are properly nested. A single stray ) or a ] closing a ( means the formatter must refuse to touch the file.
Task
Write a function that returns whether a string is balanced:
- the bracket pairs are
(),[]and{}; - every opening bracket must be closed by a bracket of the same type, and brackets must close in the reverse order they were opened;
- every other character (letters, digits, spaces, quotes…) is ignored and has no special meaning;
- the empty string is balanced.
Strings are at most 10 000 characters long, so a recursive solution can run out of stack: prefer a loop.
Function to implement
| Language | Signature |
|---|---|
| Python | def is_balanced(s: str) -> bool |
| JavaScript | function isBalanced(s) returning true or false |
A hidden driver calls your function once per test string and prints yes or no. Do not read input or print anything yourself: just define the function (helper functions are fine).
Example
is_balanced("([]{})") -> True
is_balanced("a(b)c[d]") -> True
is_balanced("(]") -> False (wrong type)
is_balanced("([)]") -> False (wrong order)
is_balanced("((") -> False (never closed)
is_balanced("") -> True
Allowed languages: python, javascript
Hints
Stuck? Hints are optional, and each one lowers the points you earn for solving this challenge.
- Hint 1Costs 10 points
- Hint 2Costs 15 points
Reveal the previous hint first
- Hint 3Costs 15 points
Reveal the previous hint first
Lessons that teach this
Stuck on the ideas rather than the puzzle? These lessons cover what you need.