Generic Code for Anagrams

suggest change
function isAnagram(left, right) {
    const leftCharacters = [...left.normalize()];
    const rightCharacters = [...right.normalize()];
    if (leftCharacters.length !== rightCharacters.length) return false;

    const frequencies = new Map();
    for (const character of leftCharacters) {
        frequencies.set(character, (frequencies.get(character) ?? 0) + 1);
    }

    for (const character of rightCharacters) {
        const remaining = frequencies.get(character);
        if (remaining === undefined) return false;
        if (remaining === 1) frequencies.delete(character);
        else frequencies.set(character, remaining - 1);
    }
    return frequencies.size === 0;
}

console.log(isAnagram("stackoverflow", "flowerovstack"));
console.log(isAnagram("stackoverflow", "flowervvstack"));
true
false

The algorithm takes O(n) expected time and O(k) space, where k is the number of distinct characters. Spreading the strings iterates by Unicode code point rather than UTF-16 code unit; locale-specific notions of anagrams may also require case folding and removal of punctuation or diacritics.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents