> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Group Anagrams Python Solution with Tests

> Tested Python solution for LeetCode 49 with 15 pytest cases. Generate a practice environment with lcpy.

LeetCode 49, Medium. Topics: Array, Hash Table, String, Sorting. [View on LeetCode](https://leetcode.com/problems/group-anagrams/description/).

Generate this problem as a practice environment: tested reference solution, 15 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 49   # by problem number
lcpy gen -s group_anagrams   # by problem name
```

## 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.

### Examples

```
Input: strs = ["eat","tea","tan","ate","nat","bat"]
Output: [["bat"],["nat","tan"],["ate","eat","tea"]]
Explanation:
- There is no string in strs that can be rearranged to form "bat".
- The strings "nat" and "tan" are anagrams as they can be rearranged to form each other.
- The strings "ate", "eat", and "tea" are anagrams as they can be rearranged to form each other.
```

```
Input: strs = [""]
Output: [[""]]
```

```
Input: strs = ["a"]
Output: [["a"]]
```

### Constraints

* `1 <= strs.length <= 10^4`
* `0 <= strs[i].length <= 100`
* `strs[i]` consists of lowercase English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/group_anagrams/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/group_anagrams/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * k) - when k > 26 use counting O(k), when k ≤ 26 use sorting O(k log k)
    # Space: O(n * k)
    def group_anagrams(self, strs: list[str]) -> list[list[str]]:
        groups: dict[str | tuple[int, ...], list[str]] = {}

        for s in strs:
            if len(s) >= 26:
                # Use counting for short strings (better time)
                # Time: O(k) - single pass through string + O(26) for tuple
                # Space: O(26) = O(1) per key
                count = [0] * 26
                for c in s:
                    count[ord(c) - ord("a")] += 1
                key: tuple[int, ...] | str = tuple(count)
            else:
                # Use sorting for long strings (better space)
                # Time: O(k log k) - sorting dominates
                # Space: O(k) per key
                key: tuple[int, ...] | str = "".join(sorted(s))

            groups.setdefault(key, []).append(s)

        return list(groups.values())
```

## Complexity

| Time                                                                          | Space     |
| ----------------------------------------------------------------------------- | --------- |
| O(n \* k) - when k > 26 use counting O(k), when k ≤ 26 use sorting O(k log k) | O(n \* k) |

## Tags

[Grind](/catalog/grind), [Blind 75](/catalog/blind-75), [NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode), [AlgoMaster 75](/catalog/algo-master-75).
