Basic Algorithm Scripting (Mutations)




I wonder how to return true or false depending on a condition result (line 23):
It should be like “if none of the items are equal, return false, otherwise, return true”.

How can I write this kind of loop? Thanks!

If you use a loop, you can check something at each iteration, if that thing is false you can return false inside the loop and break from the function. If nothing is false then the loop ends and you can return true
It can also be used inverting the return statements depending on what you need to check.
This would be the structure: (blurred in case you want to figure it from the above explanation)

for (...) {
   if (...) {
      return false;
return true;

Basically a one liner:

function mutation(arr) {

    return arr[1].toLowerCase().split('').every((letter) => arr[0].toLowerCase().indexOf(letter) >= 0);

mutation(["hello", "hey"]);

Thanks, kerafyrm02
I did not know about every method.

Using two loops (checking character by character) is bad approach in this case?

Thank you leahleen.
But how does it refer to secondArr and equalChars ?

Didn’t you want to do something like that with this part of your code?
If you let it like this it will stop at k=0 and l=0.

for (let k=0; k < equalChars.length; k++) {
      for (let l=0; l < secondArr.length; l++) {
             if(equalChars[k] !== secondArr[l]) {
                   //return false;
             } else {
              //return true;

Yes, thank you.
But I am not sure how to write a loop which compares equalChars to secondArr.
After not a short time I found this article:
This should be helpful to compare.

It is so painful to write these basic algorithms :slight_smile:

Using two nested loops would achieve the same thing.

In fact, my example and the example of using two loops is actually too slow. It would be O(n^2).

This example is O(n). Which would be significantly faster.

function mutation(arr) {

    var validLetters = {};

    for (let i = 0; i < arr[0].length; i = i + 1){
        let letter = arr[0][i].toLowerCase();
        validLetters[letter] = true;

    for (let i = 0; i < arr[1].length; i = i + 1){
       let letter = arr[1][i].toLowerCase();
       if (!validLetters[letter]){
         return false;

    return true;

1 Like

I will check it tomorrow. Thank you very much!

Incredible! You set each letter to true, and then, if it does not appear in the second array, return false.
Well done!

Hi @kerafyrm02,

I do not understand at the end of the code, Why .indexOf(letter) >= 0); ?? Greater or equal to zero.

Thank you for the help!


If letter is found, indexOf will give you an index number at where it’s found anywhere from 0 to more.

If it’s not found, then it will be less than 0. So basically it’s checking to see if letter is existent.

Thanks Phillip