Balanced Brackets

  • + 0 comments

    JS solution:

    function isBalanced(s) {
        if (s.length % 2 != 0) return "NO"
        const PAIRS = {
            "}": "{",
            "]": "[",
            ")": "("
        }
        const brackets = []
    
        for (let i = 0; i < s.length; i++) {
            if (!(s[i] in PAIRS)) {
                brackets.push(s[i])
            } else {
                let counterBracket = brackets.pop()
                if (PAIRS[s[i]] !== counterBracket) brackets.push(null)     
            }
        }
        return brackets.length > 0 ? "NO" : "YES"
    }