How to use Map In Javascript
- First we check if the lengths of both strings are equal. If not, they cannot be permutations, so we return false.
- Then we create a Map to store the character frequencies of str1 then, we iterate through str2 and decrement the frequencies in the Map.
- If a character is not found in the Map or its frequency becomes zero, we return false.
- If all characters in str2 are successfully matched, the Map will be empty, and we return true.
Example:
function arePermutations(str1, str2) {
// Check if the lengths of
// both strings are the same
if (str1.length !== str2.length) {
return false;
}
// Create a Map to store character
const charFrequencyMap = new Map();
// Fill the Map with characters
for (let char of str1) {
charFrequencyMap.set(char,
(charFrequencyMap.get(char) || 0) + 1);
}
// Iterate through str2
for (let char of str2) {
if (!charFrequencyMap.has(char)) {
// Character not found in str1
return false;
}
charFrequencyMap.set(char,
charFrequencyMap.get(char) - 1);
if (charFrequencyMap.get(char) === 0) {
charFrequencyMap.delete(char);
}
}
// If the Map is empty
// all characters in str2
//have been matched
return charFrequencyMap.size === 0;
}
// Test cases
console.log(arePermutations("abc", "cba"));
Output
true
Time complexity: O(n)
Space Complexity: 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