Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to write a JavaScript function that returns true if a portion of string 1 can be rearranged to string 2?
We need to write a function that checks if the characters from one string can be rearranged to form another string. This is essentially checking if one string contains all the characters needed to build the second string.
The function scramble(str1, str2) should return true if characters from str1 can be rearranged to match str2, otherwise false.
Problem Examples
str1 = 'cashwool', str2 = 'school' ? true (cashwool contains: c,a,s,h,w,o,o,l - enough to make 'school') str1 = 'katas', str2 = 'steak' ? false (katas missing 'e' needed for 'steak')
Method 1: Character Frequency Count (Recommended)
Count character frequencies in both strings and check if str1 has enough of each character needed for str2.
function scramble(str1, str2) {
// Count character frequencies in str1
const charCount = {};
for (let char of str1) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Check if str1 has enough characters for str2
for (let char of str2) {
if (!charCount[char] || charCount[char] === 0) {
return false;
}
charCount[char]--;
}
return true;
}
// Test cases
console.log(scramble('cashwool', 'school')); // true
console.log(scramble('katas', 'steak')); // false
console.log(scramble('scriptjava', 'javascript')); // true
true false true
Method 2: Sort and Check Substring
Sort both strings and check if the sorted shorter string is contained in the sorted longer string.
function scrambleSort(str1, str2) {
const sortedStr1 = str1.split("").sort().join("");
const sortedStr2 = str2.split("").sort().join("");
// Check if str1 contains all characters of str2
let i = 0, j = 0;
while (i < sortedStr1.length && j < sortedStr2.length) {
if (sortedStr1[i] === sortedStr2[j]) {
j++;
}
i++;
}
return j === sortedStr2.length;
}
console.log(scrambleSort('cashwool', 'school')); // true
console.log(scrambleSort('katas', 'steak')); // false
true false
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Character Count | O(n + m) | O(1) - limited charset | High |
| Sort & Check | O(n log n + m log m) | O(n + m) | Medium |
Key Points
- The character frequency method is more efficient for large strings
- Both methods handle duplicate characters correctly
- The problem is essentially checking if str1 is a "superset" of str2 in terms of character availability
Conclusion
Use the character frequency counting method for better performance. It efficiently checks if one string contains enough characters to rearrange into another string with O(n + m) time complexity.
