How to use Sorting In Javascript
- Creating a function and storing the length of strings in separate variables.
- Checking if the length of both strings is not the same then we will return false. As strings are not permutations of each other.
- If the length is the same then we will sort both the strings.
- We will check the presence of the same character in both strings in a for loop. If any of the characters get mismatched then we will return false. else we will return true at the end of the for loop.
Example:
function arePermutation(str1, str2) {
// Get lengths of both strings
let n1 = str1.length;
let n2 = str2.length;
// If length of both strings
// is not the same, then they
// cannot be permutations
if (n1 !== n2)
return false;
// Convert the strings to arrays
let ch1 = str1.split('');
let ch2 = str2.split('');
// Sort both arrays
ch1.sort();
ch2.sort();
// Compare sorted arrays
for (let i = 0; i < n1; i++)
if (ch1[i] !== ch2[i])
return false;
return true;
}
// Driver Code
let str1 = "test";
let str2 = "teat";
if (arePermutation(str1, str2))
console.log("Yes");
else
console.log("No");
Output
No
Time Complexity: O(nLogn)
Auxiliary space: O(1)
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