SDE & MLE Prep

438. Find All Anagrams in a String

Problem

Return the start indices of every substring of s that is an anagram of p, in any order.

Example: s = "cbaebabacd", p = "abc" → [0,6]

Constraints: lowercase letters; lengths ≤ 3·10⁴.

Fixed window of size len(p); compare 26-letter counts at every position (O(26) per step), collecting start indices that match.

Complexity: O(26·n).

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        k, res = len(p), []
        need, win = [0] * 26, [0] * 26
        for ch in p:
            need[ord(ch) - 97] += 1
        for r, ch in enumerate(s):
            win[ord(ch) - 97] += 1
            if r >= k:
                win[ord(s[r - k]) - 97] -= 1
            if win == need:
                res.append(r - k + 1)
        return res