I am working on a CodeWars kata that requires the code to run under a certain time limit. This code passes all the tests; but, it doesn't run fast enough. I don't know what else I can trim down or change.
Addition: I tried looking up a String.split-join solution. But, that won't work. The split will replace every occurrence of a character. I need to check for only one at a time. I even tried using the split-join with RegEx that only took one occurrence of a character. But, that was just adding more code on top of what I already had.
Putting the strings into arrays is too slow.
Someone suggested that I try a different way of looking at the problem by rearranging the characters. Maybe I need to sort them which will group the duplicate characters together.
Kata description:
If all the characters in the second string are found in the first string, then return true; otherwise, return false.
I included some test cases at the end.
function scramble(str1, str2) {
var str2Length = str2.length;
var str11 = "";
for(i = 0; i < str2Length; i++){
str11 = str1.replace(str2[i], '');
if(str11 === str1){
return false;
}
str1 = str11;
}
// If all the characters have been found in the second string, then return true.
return true;
}
scramble('rkqodlw','world');
console.log("should be true");
scramble('cedewaraaossoqqyt','codewars');
console.log("should be true");
scramble('katas','steak');
console.log("should be false");
scramble('scriptjava','javascript');
console.log("should be true");
scramble('scriptingjava','javascript');
console.log("should be true");
scramble('jscripts','javascript');
console.log("should be false");
scramble('aabbcamaomsccdd','commas');
console.log("should be true");
i
is global (missingvar
) so if the perf code usesi
too you cause an infinite loop. \$\endgroup\$