Anagram Check

Program to check if two strings are anagrams

IntermediateTopic: String Programs
Back

JavaScript Anagram Check Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Anagram: Same characters, different order
// Examples: "listen" and "silent", "evil" and "vile"

// Method 1: Sort and compare
function isAnagram1(str1, str2) {
    // Normalize: lowercase, remove spaces
    str1 = str1.toLowerCase().replace(/\s/g, '');
    str2 = str2.toLowerCase().replace(/\s/g, '');
    
    // Sort and compare
    return str1.split('').sort().join('') === 
           str2.split('').sort().join('');
}

console.log("listen & silent:", isAnagram1("listen", "silent"));
console.log("hello & world:", isAnagram1("hello", "world"));
console.log("The Morse Code & Here come dots:", 
    isAnagram1("The Morse Code", "Here come dots"));

// Method 2: Character frequency count
function isAnagram2(str1, str2) {
    str1 = str1.toLowerCase().replace(/\s/g, '');
    str2 = str2.toLowerCase().replace(/\s/g, '');
    
    if (str1.length !== str2.length) return false;
    
    let count1 = {};
    let count2 = {};
    
    // Count characters in str1
    for (let char of str1) {
        count1[char] = (count1[char] || 0) + 1;
    }
    
    // Count characters in str2
    for (let char of str2) {
        count2[char] = (count2[char] || 0) + 1;
    }
    
    // Compare counts
    for (let char in count1) {
        if (count1[char] !== count2[char]) {
            return false;
        }
    }
    
    return true;
}

console.log("\nUsing frequency:");
console.log("listen & silent:", isAnagram2("listen", "silent"));
console.log("aabb & abab:", isAnagram2("aabb", "abab"));

// Method 3: Single object count
function isAnagram3(str1, str2) {
    str1 = str1.toLowerCase().replace(/\s/g, '');
    str2 = str2.toLowerCase().replace(/\s/g, '');
    
    if (str1.length !== str2.length) return false;
    
    let count = {};
    
    // Increment for str1
    for (let char of str1) {
        count[char] = (count[char] || 0) + 1;
    }
    
    // Decrement for str2
    for (let char of str2) {
        if (!count[char]) return false;
        count[char]--;
    }
    
    return true;
}

console.log("\nSingle object:");
console.log("evil & vile:", isAnagram3("evil", "vile"));
Output
listen & silent: true
hello & world: false
The Morse Code & Here come dots: true

Using frequency:
listen & silent: true
aabb & abab: true

Single object:
evil & vile: true

Understanding Anagram Check

This program demonstrates different methods to check if two strings are anagrams.

Anagram Definition

Two strings are anagrams if:

They contain same characters
Same frequency of each character
Different order

Examples:

"listen" ↔ "silent"
"evil" ↔ "vile"
"The Morse Code" ↔ "Here come dots"

Method 1: Sort and Compare

Sort both strings and compare:

str1.split('').sort().join('') === 
str2.split('').sort().join('');

Steps:

1.Convert to arrays
2.Sort both
3.Join back to strings
4.Compare

Time Complexity:

O(n log n) due to sort

Method 2: Character Frequency

Count character occurrences:

let count1 = {};
for (let char of str1) {
    count1[char] = (count1[char] || 0) + 1;
}
// Compare counts

Object Counting:

count[char] || 0: Default to 0 if undefined
Increment count for each character

Method 3: Single Object

More efficient:

for (let char of str1) {
    count[char] = (count[char] || 0) + 1;
}


// Decrement for str2
for (let char of str2) {
    if (!count[char]) return false;
    count[char]--;
}
// Increment for str1

How it works:

Increment counts for str1
Decrement counts for str2
If all become 0, they're anagrams

Time Complexity:

Sort method: O(n log n)
Frequency methods: O(n) - Better!

Edge Cases:

Different lengths: Not anagrams
Case sensitivity: Normalize with toLowerCase()
Spaces: Remove with replace()

When to Use:

-

Sort

: Simple, readable

-

Frequency

: More efficient, handles duplicates well

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Table of Contents