Code Lab

Timer: 15 min, like in an interview. Hints and autocomplete are off while it runs

Balanced brackets

HardStrings15 min

Write a function isBalanced(text) that returns true when the brackets in the string text are balanced, and false otherwise.

  • There are three kinds of brackets: (), [] and {}. Every other character is skipped: 'if (a[0]) { b() }' is balanced.
  • Every opening bracket needs a closing bracket of the same kind after it: '(]' is not balanced.
  • Brackets close in the reverse order of opening: '([)]' is not balanced, '([])' is.
  • A closing bracket with no open bracket before it makes the text not balanced: ')(' is not balanced.
  • A string with no brackets, also an empty string, is balanced.
  • The text can be long, up to 100 000 characters, and brackets can nest 50 000 levels deep. Your code must finish in time.

Examples

isBalanced('([]{})')

Returns true

isBalanced('([)]')

Returns false

isBalanced('if (a[0]) { b() }')

Returns true

Asked at Swiggy · Source

Loading the editor...
  1. InputisBalanced('([]{})')
    Expectedtrue
  2. InputisBalanced('([)]')
    Expectedfalse
  3. InputisBalanced('if (a[0]) { b() }')
    Expectedtrue

Hidden tests run on Submit