• + 0 comments

    It can be optimized with regex, but here is a solution that can help solving many balancing issues. the idea is to strip all the valid brackets, till we are left with no valid ones. Solution is in Typescript:

    function isBalanced(s: string): string {
        // Write your code here
        let replacedCount = Infinity;
        while (replacedCount > 0) {
            const start = s.length
            s = s.replace('()', '').replace('{}', '').replace('[]', '');
            const end = s.length;
            replacedCount = start - end;
        }
      
      return s.length === 0 ? 'YES' : 'NO';
    }