# 49. Group Anagrams

{% hint style="info" %}
针对这种在顺序上做文章的，首先要进行排序，再做操作

Key idea: `hashmap()`
{% endhint %}

### Solution:

1. traverse all elements of strs
2. sort each word by letters
3. add to hashmap, the words composed with same letters will be mapped to same key-item
4. covert to `result` list

```python
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        d = {}
        for x in strs:
            tmp = sorted(x)
            tmp = "".join(tmp)
            if tmp not in d:
                d[tmp] = [x]
            else:
                d[tmp].append(x)
        
        result = []
        for key in d.keys():
            result.append(d[key])
            
        return result
```

Time complexity = $$O(n)$$ , if `sorted()` is $$O(1)$$ , Space complesity = $$O(n)$$&#x20;

{% hint style="danger" %}
`list.sort()` change the list, `sorted(list)` doesn't change the list.

`list.reverse()` change the list, `reversed(list)` doesn't change the list.

`sorted(string)` converts string to a list.

`separator.join(list)` means convert list to a string combining by separator. For example, `"".join(['a', 'b', 'c']) = "abc".`
{% endhint %}


---

# 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://r24zeng.gitbook.io/leetcode-notebook/zhong-yu-shua-dao-100-dao-le-wo-shi-fen-shui-ling/bu-chong-120-dao/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.
