Checking for string anagrams JavaScript

In this problem statement, our aim is to check for string anagrams with the help of Javascript functionalities. So for solving this problem first we need to understand the problem in simple terms.

Understanding the Problem Statement

We have given two strings as input and our main aim is to check if the strings are anagrams of each other. If they are anagrams then return true otherwise return false.

What are Anagrams?

An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example, "silent" and "listen" are anagrams because they contain the same letters with the same frequency - both have 6 letters and the same character count.

SILENT rearrange LISTEN Letters: S, I, L, E, N, T Letters: L, I, S, T, E, N ? Same letters = Anagrams

Algorithm

Step 1 ? Declare a function called isAnagram which takes two string arguments.

Step 2 ? Convert both strings to lowercase and remove any non-word characters to normalize the input.

Step 3 ? Split each string into character arrays, sort them, and join them back into strings.

Step 4 ? Compare the sorted strings and return true if they are equal, false otherwise.

Implementation

// Function to check if two strings are anagrams
function isAnagram(str1, str2) {
   // Remove non-word characters and convert to lowercase
   const clean1 = str1.replace(/[^\w]/g, "").toLowerCase();
   const clean2 = str2.replace(/[^\w]/g, "").toLowerCase();
   
   // Sort characters and compare
   return clean1.split("").sort().join("") === clean2.split("").sort().join("");
}

// Test examples
const result1 = isAnagram("silent", "listen");
const result2 = isAnagram("tutorials", "uttoslair");
const result3 = isAnagram("hello", "bello");

console.log("'silent' and 'listen':", result1);
console.log("'tutorials' and 'uttoslair':", result2);
console.log("'hello' and 'bello':", result3);
'silent' and 'listen': true
'tutorials' and 'uttoslair': true
'hello' and 'bello': false

Alternative Approach: Character Frequency Count

For better performance, we can use a frequency counting approach instead of sorting:

function isAnagramFrequency(str1, str2) {
    const clean1 = str1.replace(/[^\w]/g, "").toLowerCase();
    const clean2 = str2.replace(/[^\w]/g, "").toLowerCase();
    
    if (clean1.length !== clean2.length) return false;
    
    const charCount = {};
    
    // Count characters in first string
    for (let char of clean1) {
        charCount[char] = (charCount[char] || 0) + 1;
    }
    
    // Subtract characters from second string
    for (let char of clean2) {
        if (!charCount[char]) return false;
        charCount[char]--;
    }
    
    return true;
}

console.log("Frequency method:", isAnagramFrequency("anagram", "nagaram"));
Frequency method: true

Complexity Analysis

Method Time Complexity Space Complexity
Sorting Method O(n log n) O(n)
Frequency Count O(n) O(1) - limited by alphabet size

Conclusion

Both approaches effectively check for anagrams in JavaScript. The sorting method is simpler to implement, while the frequency counting method offers better time complexity for large strings.

Updated on: 2026-03-15T23:19:00+05:30

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements