Please help me understand why my code is bad (javascript, Scramblies task)

3393 views javascript
2

I am trying to solve the following task:

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

The code I have written goes through the initial tests but fails on the final attempt with the following error: "Execution Timed Out (12000 ms)". Could you please hint what is wrong here?

function scramble(str1, str2) {
   
let array1 = str1.split("").sort(); 
let array2 = str2.split("").sort();
let count = 0;
 
for(let a = 0; a <= array1.length && count < array2.length; a++) {
    if(array2[count] === array1[a]){
      count++;  
      }
  }
  
return (count === array2.length);
}

answered question

Can you add examples of string pairs for which the function would return true/false?

What's the final test that's failing?

1 Answer

12

if a portion of str1 characters can be rearranged to match str2 doesn't this mean str2 has to include all of the str1's characters? Your function probably isn't failing it just requires so much time to operate on the final test.

function scramble(str1, str2) {
    for (const letter of str2) {
        if (!str1.includes(letter)) {
            return false;
        }
    }
    return true;
}

posted this

Have an answer?

JD

Please login first before posting an answer.