patternjavascriptMinor
Checking if string characters can be arranged to form another string
Viewed 0 times
cancheckingarrangedanothercharactersformstring
Problem
I am working on a code project that checks if all the characters in
For example, here are some test cases below and the intended return:
I have a working code solution, but I'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.
I originally used a basic for loop (with the array length cached as a variable and not in the
but tried the
Are there any other specific tricks I can implement on my code that can speed it up and still retain the original functionality?
str1 can be arranged to form another string (str2). If all the characters in str2 are present in str1 (including any repeated characters in str2, i.e. if str2 has two 'a' characters, str1 must correspondingly have two as well), then the function returns true.For example, here are some test cases below and the intended return:
str1 = 'rkqodlw'
str2 = 'world'
Expected: true
str1 = 'cedewaraaossoqqyt'
str2 = 'codewars'
Expected: true
str1 = 'katas'
str2 = 'steak'
Expected: false
str1 = 'scriptjava'
str2 = 'javascript'
Expected: true
I have a working code solution, but I'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.
function stringscrambling(str1, str2) {
var arr1 = str1.split('');
var arr2 = str2.split('');
var index;
var l = arr2.length;
while (l--) {
index = arr1.indexOf(arr2[l]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
I originally used a basic for loop (with the array length cached as a variable and not in the
for statement) as follows:for (var i = 0, l = arr2.length; i -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
but tried the
while-loop in reverse as I read that specific looping would offer a bit better in terms of benchmarked performance. The change in loop offered a negligible performance upgrade.Are there any other specific tricks I can implement on my code that can speed it up and still retain the original functionality?
Solution
The way to improve your performance is to use a better algorithm, specifically, sort both strings and compare:
function stringscrambling(str1, str2) {
var sort1 = str1.split('').sort().join('');
var sort2 = str2.split('').sort().join('');
return sort1 === sort2;
}Code Snippets
function stringscrambling(str1, str2) {
var sort1 = str1.split('').sort().join('');
var sort2 = str2.split('').sort().join('');
return sort1 === sort2;
}Context
StackExchange Code Review Q#117298, answer score: 7
Revisions (0)
No revisions yet.