This is basically based on the following question on stackoverflow which was based on a codewars assignment that can be found here
Problem statement
Complete the function
scramble(str1, str2)
that returnstrue
if a portion ofstr1
characters can be rearranged to matchstr2
, otherwise returnsfalse
.
Notes:
- Only lower case letters will be used (a-z). No punctuation or digits will be included.
- Performance needs to be considered
My solution
function scramble(str1, str2) {
if (str1.length < str2.length) {
return false;
}
const set = new Set([...str2]);
return Array.from( set ).every( letter => str2.split(letter).length <= str1.split(letter).length );
}
As with the original question on SO, my question would be if there are more efficient ways of completing the assignment. I am mainly worried about the string.split
, but I didn't know of any other method that might be faster (I know I should substract 1 to get the actual letter count, but it doesn't matter for this usecase)