> For the complete documentation index, see [llms.txt](https://algorithm.prettylog.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/string/49.-group-anagrams.md).

# 49. Group Anagrams

{% embed url="<https://leetcode.com/problems/group-anagrams/description/>" %}

### 2nd try

> time: O(n x m)

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

```jsx
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)

```jsx
/**
 * @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);
};
```
