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

# Find All Anagrams in a String Python Solution

> Tested Python solution for LeetCode 438 with 12 pytest cases. Generate a practice environment with lcpy.

LeetCode 438, Medium. Topics: Hash Table, String, Sliding Window. [View on LeetCode](https://leetcode.com/problems/find-all-anagrams-in-a-string/description/).

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

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

## Problem

Given two strings `s` and `p`, return an array of all the start indices of `p`'s anagrams in `s`. You may 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: s = "cbaebabacd", p = "abc"
Output: [0,6]
```

**Explanation:**
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

```
Input: s = "abab", p = "ab"
Output: [0,1,2]
```

**Explanation:**
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

### Constraints

* 1 \<= s.length, p.length \<= 3 \* 10^4
* s and p consist of lowercase English letters.

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import Counter


class Solution:
    """
    Sliding Window with Character Frequency Counting

    Algorithm:
    1. Count character frequencies in pattern p
    2. Use sliding window of size len(p) on string s
    3. Maintain frequency count of current window
    4. When frequencies match, record start index

    ASCII Visualization:
    s = "cbaebabacd", p = "abc" (need: a=1, b=1, c=1)

    Window positions:
    [cba]ebabacd  -> {c:1, b:1, a:1} ✓ matches -> index 0
    c[bae]babacd  -> {b:1, a:1, e:1} ✗
    cb[aeb]abacd  -> {a:1, e:1, b:1} ✗
    cba[eba]bacd  -> {e:1, b:1, a:1} ✗
    cbae[bab]acd  -> {b:2, a:1} ✗
    cbaeb[aba]cd  -> {a:2, b:1} ✗
    cbaeba[bac]d  -> {b:1, a:1, c:1} ✓ matches -> index 6
    """

    # Time: O(n) where n is length of s
    # Space: O(1) - at most 26 lowercase letters
    def find_anagrams(self, s: str, p: str) -> list[int]:
        if len(p) > len(s):
            return []

        result = []
        p_count = Counter(p)
        window_count = Counter(s[: len(p)])

        # Check first window
        if window_count == p_count:
            result.append(0)

        # Slide window
        for i in range(len(p), len(s)):
            # Add new character
            window_count[s[i]] += 1

            # Remove old character
            left_char = s[i - len(p)]
            window_count[left_char] -= 1
            if window_count[left_char] == 0:
                del window_count[left_char]

            # Check if current window is anagram
            if window_count == p_count:
                result.append(i - len(p) + 1)

        return result
```

## Complexity

| Time                        | Space                               |
| --------------------------- | ----------------------------------- |
| O(n) where n is length of s | O(1) - at most 26 lowercase letters |

## Tags

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