Python coding

Every place an anagram starts

Given a string s and a non-empty string p, both made of lowercase letters, return every index i such that the substring of s that starts at i and has length len(p) is a rearrangement of p: the same letters, the same number of times, in any order. Return the indices in increasing order; overlapping matches all count. If p is longer than s, return [].

Aim for O(len(s) + len(p)) time.

Besides the tests, one large input (8,000-letter s, 3,000-letter p) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • anagram_starts("dogodgxgod", "god") → [0,2,3,7]
  • anagram_starts("abab", "ab") → [0,1,2]
  • anagram_starts("hello", "xyz") → []
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Every candidate has exactly len(p) letters: a fixed-size window. Neighboring windows differ by one letter in and one letter out.

Hint 2

Keep the window's letter counts and update them in O(1) per step, instead of recounting or sorting each window.

Hint 3

To avoid comparing two count maps each step, track missing, the letters of p the window still lacks. A full window with missing == 0 is a match.

Solution and why it works
pythonO(n + m), n = len(s), m = len(p) · O(A), A = alphabet size (26)
from collections import Counter

def anagram_starts(s: str, p: str) -> list[int]:
    m = len(p)
    owed = Counter(p)                    # letters of p the window still lacks
    missing = m
    starts = []
    for right, ch in enumerate(s):
        if owed[ch] > 0:
            missing -= 1
        owed[ch] -= 1
        if right >= m:                   # keep the window at exactly m letters
            out = s[right - m]
            owed[out] += 1
            if owed[out] > 0:
                missing += 1
        if missing == 0:                 # m letters that cover p are a rearrangement of p
            starts.append(right - m + 1)
    return starts

The window always holds exactly len(p) letters, so it is a rearrangement of p exactly when it covers every letter of p. One missing counter answers that in O(1) as one letter enters and one leaves: O(n + m) in total. Sorting or recounting every window costs O(n·m). The trap is comparing sets instead of counts: "aab" and "abb" use the same letters, but neither is a rearrangement of the other.

Related lab: Sliding window, step by step