Search code examples
javascriptloopsbracketsrosetta-code

Is this a valid Javascript solution for Rosetta Code: Balanced Brackets?


Description of the problem: https://rosettacode.org/wiki/Balanced_brackets

For some reason, Freecodecamp thinks my solution isn't valid to include in their directory, I just want some confirmation https://forum.freecodecamp.org/t/additional-solution-for-rosetta-code-balanced-brackets/426226

What I realized is that in a system of balanced brackets, there must always be at least one substring equal to [] as balanced brackets require opposite brackets that face towards each other, and there can be no spaces. Additionally, all instances of [] can be repeatedly removed until there is an empty string.

I tried this code on all test cases that I could find, and it works each time.

function isBalanced(str) {
  while (true) {
    str = str.replace('[]', ''); 
    if(str.length==0){
      return true;
    }
    if(str[0]==']'||str[str.length-1]=='['){
      return false;
    }
  }
}

Solution

  • Not only is it a valid approach, it is also already part of the rosetta code javascript solutions. Balanced_brackets#ES5

    function isBalanced(str) {
        var a = str, b
        do { b = a, a = a.replace(/\[\]/g, '') } while (a != b)
        return !a
    }