0

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;
    }
  }
}
  • Use a stack. Everytime you have an open bracket, push. When you find a closed bracket pop. At the end of the string see if the stack is empty. – Brenden Oct 23 '20 at 16:47
  • 1
    _"I tried this code on all test cases that I could find, and it works each time."_ - So what's the problem/question? – Andreas Oct 23 '20 at 16:48
  • 1
    This solution will work, but it is not efficient, as you call `replace` repeatedly, which scans the string as many times, while this can be done with one scan. – trincot Oct 23 '20 at 16:50
  • For some reason, Freecodecamp thinks my solution isn't valid, I just want some confirmation https://forum.freecodecamp.org/t/additional-solution-for-rosetta-code-balanced-brackets/426226 – Yuval Levental Oct 23 '20 at 16:50
  • @trincot I will check it out, thanks – Yuval Levental Oct 23 '20 at 16:51
  • *"For some reason..."*: that was before you fixed the bug you posted there. – trincot Oct 23 '20 at 16:57
  • @trincot I pinged them and they didn't respond. Maybe I will try again later then on FCC. – Yuval Levental Oct 23 '20 at 17:13

2 Answers2

1

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
}
steviestickman
  • 1,132
  • 6
  • 17
0

Here is a non regex solution.

const balanced = (string) => {
  let stack = [];

  for (let i = 0; i < string.length; i++) {
    const char = string[i];
    
    if (char === '[') {
        stack.push('')
    } else if (char === ']') {
        stack.pop()
    }
  }

  return stack.length === 0;
};

[
  ['[]', true],
  ['[][]', true],
  ['[[][]]', true],
  ['][', false],
  ['][][', false],
  ['[]][[]', false]
].forEach(([value, expected]) => {
  console.log(`balanced(${value}) === ${balanced(value)} expected ${expected}`);
})
Brenden
  • 1,947
  • 1
  • 12
  • 10