Tom on the Internet
← Back

Group Anagrams

medium
Hash Table String

<Code />

function groupAnagrams(strs) {
    let values = {};
    for (let str of strs) {
        let counts = new Array(26).fill(0);
        for (let char of str) {
            counts[char.charCodeAt() - "a".charCodeAt()] += 1;
        }
        let key = counts.join("");
        if (values[key]) {
            values[key].push(str);
        } else {
            values[key] = [str];
        }
    }
    return Object.values(values);
}

Thoughts

Anagrams again. Like in the previous question, we can figure out if two strings are anagrams by making a list of their letter counts. This ensure fixed space. The key here is that we don't ever sort. Sorting is O(n log n), so it breaks our O(n). In a real app I'd probably sort, or at least break out a function for getting the "key".