1
\$\begingroup\$

This checks whether one string has all the chars in another string to make up that exact string. Counts matter so for, for example, str1 = 'abcdgbff' str2 ='aaabb' should return false because str1 only has one 'a' and 'b'.

How can I optimize my code further?

function scramble(str1, str2) {
 for (let i of str1) {
 if (str2.indexOf(i) != -1) {
 str2 = str2.slice(0, (str2.indexOf(i))) + str2.slice(str2.indexOf(i) + 1);
 }
 }
 return str2.length === 0;
}
// Example:
console.log(scramble('abcdgbff', 'aaabb')); // false

le_m
1,93510 silver badges15 bronze badges
asked Apr 22, 2017 at 22:43
\$\endgroup\$
0

2 Answers 2

1
\$\begingroup\$

If your input strings are of length n, your current implementation has a cubic runtime complexity O(n3). This could become an issue for longer strings.

I recommend to split counting character frequencies and comparing those counts into two separate steps with nearly linear complexity O(n):

// Count characters in 'str':
function frequencies(str) {
 let result = {};
 for (let chr of str) {
 result[chr] = (result[chr] || 0) + 1;
 }
 return result;
}
// Check if 'str1' contains all characters of 'str2':
function scramble(str1, str2) {
 let frequencies1 = frequencies(str1);
 let frequencies2 = frequencies(str2);
 return Object.entries(frequencies2).every(([chr2, frequency2]) =>
 frequencies1[chr2] >= frequency2
 );
}
// Examples:
console.log(scramble("abc", "cba"));
console.log(scramble("aa", "aaaa"));
console.log(scramble("123", "234"));

answered Apr 23, 2017 at 2:26
\$\endgroup\$
0
-1
\$\begingroup\$

I can't program in JavaScript but i will tell you, your dealing with strings, so if you look at the type of input and know that the third letter into a word is usualy a vowl, but the last is usually a consent, then you can try to make your code error/False statement as fast as possible, if you choose to measure length then chose Consent positions to compare first.

answered Apr 24, 2017 at 6:43
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.