Count characters
- Creating a counting array of size 256. In which we are counting the number of characters present in both of the strings in two different array.
- If length of the strings are not same we will return false.
- We are using for loop for comparing the count of character if the count is not same then we will return false else a the end of for loop it will return true.
Example:
let NO_OF_CHARS = 256;
function arePermutation(str1, str2) {
// Create 2 count arrays
// and initialize all values as 0
let count1 = Array(NO_OF_CHARS).fill(0);
let count2 = Array(NO_OF_CHARS).fill(0);
if (str1.length !== str2.length)
return false;
for (let i = 0; i < str1.length && i < str2.length; i++) {
count1[str1[i].charCodeAt(0)]++;
count2[str2[i].charCodeAt(0)]++;
}
// Compare count arrays
for (let i = 0; i < NO_OF_CHARS; i++) {
if (count1[i] !== count2[i])
return false;
}
return true;
}
// Driver code
let str1 = "geeks";
let str2 = "geeks";
if (arePermutation(str1, str2))
console.log("Yes");
else
console.log("No");
Output
Yes
Time Complexity: O(n)
Auxiliary space: O(n).
Check if two strings are permutation of each other in JavaScript
In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation.
Example:
Input: "pqrs" , "rpqs"
Output: True
Explanation: Both strings have a same number of characters.
These are the approaches by using these we can Check if two strings are permutations of each other or not:
Table of Content
- Using Sorting
- Count characters
- Using Map
- Using XOR Operation