# 49. Group Anagrams

Given an array of strings, group anagrams together.

**Example:**

```
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
Output:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]
```

**Note:**

* All inputs will be in lowercase.
* The order of your output does not matter.

## Thoughts

给一些单词，让把出现相同字符的单词放在一组。判断是否permutation除了用count map检测每个元素是否都在, 还可以用 sorting配合hash table。

## Code

```python
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        m = collections.defaultdict(list)
        for s in strs:
            # m[''.join(sorted(s))].append(s)
            cnt = [0] * 26
            for c in s:
                cnt[ord(c) - ord('a')] += 1
            m[tuple(cnt)].append(s)
        return m.values()
```

```java
class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] cs = str.toCharArray();
            Arrays.sort(cs);
            String keyStr = String.valueOf(cs);
            if (map.containsKey(keyStr)) {
                map.get(keyStr).add(str);
            } else {
                map.put(keyStr, new ArrayList<>());
                map.get(keyStr).add(str);
            }
        }
        List<List<String>> res = new ArrayList<>();
        for (String str : map.keySet()) {
            res.add(map.get(str));
        }
        return res;
    }
}
```

## Analysis

时间复杂度O(nlgn).


---

# 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://hao-fu-1.gitbook.io/oj/hash/jian-guo/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.
