Stacks: Balanced Brackets

  • + 0 comments

    JavaScript Solution: ========= PSEUDOCODE ========== 1. Take one empty stack and a variable name valid with true initial value 2. Travell to each bracket of the input 3. if we are having left bracket push it into the stack 4. if we are having right bracket , then pop a bracket from the stack. . check if the poped bracked and the right bracket are compliment to eachother or not OR check stack is empty , and update the variable valid accordingly. . complete it for all three type of right bracket 5. if valid == true and stack is empty return 'YES' otherwise return 'NO'.

    Here is working code :

    function isBalanced(S) {
        let valid = true
        let stack = []
        for(let c of S){
            if(c=='(' || c=='[' || c=='{') stack.push(c)  
            else if(c == ')'){
                 valid = (stack.length === 0 || stack.pop() != '(') ? false : valid
            }
            else if(c == ']'){
                 valid = (stack.length === 0 || stack.pop() != '[' ) ? false : valid
            }
            else if(c == '}'){
                 valid = (stack.length === 0 || stack.pop() != '{' ) ? false : valid
            }
        }
        return  (valid && stack.length ===0 ) ? 'YES' : 'NO'
    }