# 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);
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/string/49.-group-anagrams.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
