Balanced Brackets

  • + 0 comments

    JavaScript Solution:-

    function isBalanced(s) {
        let stack = [];
        let matchingBrackets = {
            '(': ')',
            '{': '}',
            '[': ']'
        };
        
        for (let char of s) {
            if (matchingBrackets[char]) {
                stack.push(char);
            } else {
                let top = stack.pop();
                if (matchingBrackets[top] !== char) {
                    return 'NO';
                }
            }
        }
        return stack.length === 0 ? 'YES' : 'NO';
    }