> For the complete documentation index, see [llms.txt](https://joshualbarb.gitbook.io/leetcode-problems/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://joshualbarb.gitbook.io/leetcode-problems/hash-table/group-anagrams.md).

# Group Anagrams

## Problem

Given an array of strings `strs`, group **the anagrams** together. You can return the answer in **any order**.

An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

{% hint style="info" %}
For example:

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

{% endhint %}

## Solution

```
class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        _map = {}
        
        for i in strs:
            sorted_word = ''.join(sorted(i))
            if sorted_word not in _map:
                _map[sorted_word] = [i]
            elif sorted_word in _map:
                _map[sorted_word].append(i)
        return list(_map.values())
        
#anagrams will map to the same string if characters in
#the string are sorted

#we're going to iterate through the array of words and
#at each word, sort the letters and check if that 
#sorted word exists in the hash map


#Time: O(w*n*log n) where w is the number of words and
#n is the length of the longest word
#Space: O(w*n)
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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://joshualbarb.gitbook.io/leetcode-problems/hash-table/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.
