49. Group Anagrams

2nd try

time: O(n x m)

space: O(n) for answers, and 26 length arrays

var groupAnagrams = function (strs) {
    const memo = {};

    for (let i = 0; i < strs.length; i++) {
        const word = strs[i];
        const arr = new Array(26).fill(0);

        for (const c of word) {
            const code = c.charCodeAt();
            arr[code - 'a'.charCodeAt()]++;
        }

        const hashed = arr.join();
        if (memo[hashed] === undefined) {
            memo[hashed] = [];
        }

        memo[hashed].push(word);
    }

    return Object.values(memo);
};

1st try

time: O(n x mlogm)

space: O(n)

/**
 * @param {string[]} strs
 * @return {string[][]}
 */
var groupAnagrams = function (strs) {
    const memo = {};

    for (let i = 0; i < strs.length; i++) {
        const word = strs[i];
        const sorted = [...word].sort((a, b) => {
            return a.localeCompare(b)
        }
        ).join('');

        if (memo[sorted] === undefined) {
            memo[sorted] = [];
        }

        memo[sorted].push(word);
    }

    return Object.values(memo);
};

Last updated