I don't know why this code works, challenge: mutations

function mutation(arr) {
  let first = arr[0].toUpperCase();
  let second = arr[1].toUpperCase();
  let lengthOfArr = 0;
  for (let i=0; i<second.length; i++) {
    for (let j=0; j<first.length; j++) {
      if (second[i] === first[j]) {
        lengthOfArr++;
        break;
      }
    }
  }
  console.log(lengthOfArr);
  if (lengthOfArr === second.length) {
    return true;
  } else {
    return false;
  }
}

console.log(mutation(["helo", "hello"])); //returns true, and the test passes??!?

link to the challenge : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations

What part doesn’t make sense to you?

The challenge says:

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

But that is wrong in my code, for example “helo”(first element of the array) and “hello”(second element of the array), the first element doesn’t contain all the elements in the second one, the first still misses an "l"

It’s finding the same “l” twice. Adding a comparison for the length of the strings would get the correct result for “hello” and “helo”, but it would give you the wrong result for “hello” and “heloo”. You want to check that each string has the same number of each letter.

but the test is passed? why!?

Basic Algorithm Scripting: MutationsPassed

I looked at the challenge and by the definition of the challenge, “hello” and “helo” should return true because this challenge only cares that they have the same letters, not how many times those letters are used.

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

1 Like