Balanced Brackets

  • + 1 comment

    Using a stack is unnecessary. We can simply match pairs of brackets using Regex and remove them from the string until the string is gone. If we ever don't find a match or if the string length is not an even number we can return 'NO'

    Here's a Javascript solution:

    function isBalanced(s) {
        do {
            const n = s.replace(/(\[\]|{}|\(\))/g, '')
            if (n.length === s.length || s.length % 2) {
                return 'NO'
            }
            s = n
        } while (s.length)
        return 'YES'
    }