Mastery Points
0

Anagram Detection in dsa

Context & Logic

Two strings are anagrams of each other if they contain the same characters with the same frequencies, just in a different order.

Example

function isAnagram(s, t) {
    if (s.length !== t.length) return false;
    const count = {};
    for (let char of s) count[char] = (count[char] || 0) + 1;
    for (let char of t) {
        if (!count[char]) return false;
        count[char]--;
    }
    return true;
}

Step-by-Step Logic

1

Check if lengths are different; if so, they aren't anagrams.

2

Use a frequency map (object or Map) to count characters in the first string.

3

Iterate through the second string and decrement counts from the map.

4

If a character is missing or count drops below zero, return false.

Complexity Metrics

Time Efficiency

O(n)

Memory Footprint

O(k) where k is the character set size