No Repeats Please does not pass

Hi guys, my solution passes in VSCode, but not in FCC, can you help me with this?

const combinations = [];
const permAlone= function(rs, bs = "") {
  // console.log(`Rest: ${rs}, Base: ${bs}`);
  let base = bs.split("");
  let rest = rs.split("");

  if (rest.length === 1) {
    combinations.push(base.concat([rest[0]]));
  }
  if (rest.length === 2) {
    combinations.push(base.concat([rest[0], rest[1]]));
    combinations.push(base.concat([rest[1], rest[0]]));
  } else {
    for (let i = 0; i < rest.length; i++) { 
      permAlone( rest.slice(0, i).concat(rest.slice(i + 1, rest.length)).join(""),
        base.concat(rest[i]).join("")
      );
    }
  }
  let final = combinations.map(entry => {
      return entry.some((el, index, array) => {
        if (array[index] === array[index + 1]) return true;
      });
    }).filter(el => el === false).length;
  return final;
};
permAlone("aabb");

I must say, this was one of the most challenging algorithms so far, but I had a lot of fun doing it. As usual, there are more than a few improvements that I could make, and I’d like to know which ones…

const combinations = [];

This global variable is a problem because it does not get reset back to an empty array between tests. This is why it is always better to not use global variables as you don’t know how other code segments might be changing them.

Once you resolve the above, you will run into another problem. Your algorithm is very inefficient. The one test which will almost certainly fail is permAlone(“zzzzzzzz”). Even on my local machine, it takes well over 30 seconds to return a value. You are performing many iterations (especially with the following code) which can be reduced with a better algorithm.

  let final = combinations.map(entry => {
      return entry.some((el, index, array) => {
        if (array[index] === array[index + 1]) return true;
      });
    }).filter(el => el === false).length;

Thank you @RandellDawson for prompt reply .
Yes, I am not very proud with the final part of my code, I just finished it, and wanted to improve it later. :wrench: But I wan’t to ask, in this scenario regarding recursive functions, it seems not an easy way to find the right place for this global variable, as it would be constantly redeclared. What could be the fix here, without redoing most of the code?

You could add a 3rd parameter to your permAlone function which would be combinations and set it to a default value of an empty array. Then inside the for loop, you would just pass combinations as a 3rd argument to the permAlone function.

1 Like