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
Are the strings anagrams in JavaScript
Two strings are said to be anagrams of each other if by rearranging, rephrasing or shuffling the letters of one string we can form the other string. Both strings must contain exactly the same characters with the same frequency.
For example, 'something' and 'emosghtin' are anagrams of each other because they contain the same letters with the same count.
We need to write a JavaScript function that takes two strings and returns true if they are anagrams of each other, false otherwise.
Method 1: Character Frequency Count
This approach counts the frequency of each character in both strings and compares them:
const str1 = "something";
const str2 = "emosghtin";
const validAnagram = (str1 = '', str2 = '') => {
let obj1 = {};
let obj2 = {};
if (str1.length !== str2.length) {
return false;
}
for (let char of str1) {
obj1[char] = (obj1[char] || 0) + 1;
}
for (let char of str2) {
obj2[char] = (obj2[char] || 0) + 1;
}
for (let val in obj1) {
if (!(val in obj2) || (obj2[val] !== obj1[val])) {
return false;
}
}
return true;
};
console.log(validAnagram(str1, str2));
true
Method 2: Sorting Approach
A simpler approach is to sort both strings and compare them:
const isAnagram = (str1, str2) => {
if (str1.length !== str2.length) {
return false;
}
return str1.split('').sort().join('') === str2.split('').sort().join('');
};
console.log(isAnagram("listen", "silent"));
console.log(isAnagram("hello", "world"));
console.log(isAnagram("race", "care"));
true false true
Method 3: Single Object Approach
More efficient approach using only one object to count characters:
const checkAnagram = (str1, str2) => {
if (str1.length !== str2.length) {
return false;
}
const charCount = {};
// Count characters in first string
for (let char of str1) {
charCount[char] = (charCount[char] || 0) + 1;
}
// Decrease count for second string
for (let char of str2) {
if (!charCount[char]) {
return false;
}
charCount[char]--;
}
return true;
};
console.log(checkAnagram("anagram", "nagaram"));
console.log(checkAnagram("rat", "car"));
true false
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Character Frequency | O(n) | O(n) | Medium |
| Sorting | O(n log n) | O(n) | High |
| Single Object | O(n) | O(n) | High |
Conclusion
The single object approach is most efficient with O(n) time complexity. The sorting method is simplest to understand but slower. Choose based on your performance requirements and code readability preferences.
