Tom on the Internet
← Back

Valid Anagram

easy
Hash Table String

<Code />

function isAnagram(s, t) {
    if (s.length !== t.length) {
        return false;
    }
    let seen = new Array(26).fill(0);
    for (let i = 0; i < s.length; i++) {
        seen[s.charCodeAt(i) - "a".charCodeAt(0)]++;
        seen[t.charCodeAt(i) - "a".charCodeAt(0)]--;
    }
    return seen.every((val) => val === 0);
}

Thoughts

To figure out if two strings are anagrams, the most obvious solution is to sort the characters of each string and then compare them. That's a pretty efficient solution and it's what I would do in a production application. A more efficient solution could be to use a hash map to calculate the count of each letter. Then ensure that both hash maps have the same counts. But this solution is remarkable. It uses a single array to store the counts. There's no hashing. You either increment or decrement. At the end, every value will be 0.