An in-browser code editor wants to underline unbalanced brackets. Write isBalanced(code), which returns true if every bracket in code is properly matched.
There are three bracket pairs: (), [] and {}. Every other character (letters, spaces, operators, quotes) is ignored. A string is balanced when:
isBalanced('const f = (a) => { return [a, b]; }'); // true
isBalanced('if (x) { y[0] = (1 + 2); }'); // true
isBalanced('call(arr[0)]'); // false (wrong nesting)
isBalanced('{ open: true'); // false (never closed)
isBalanced('done) '); // false (closes without opening)
isBalanced('no brackets at all'); // true
isBalanced(''); // true
code can be up to 10⁶ characters long.Spotted a mistake or a rights concern? Report an issue