← Back to Algorithms, page 2

algorithms-0023 · Medium mid

Find all anagrams of a pattern in a string: return every start index where a permutation of p appears in s.

An anagram of p has the same letter counts as p, so slide a window of length len(p) over s and keep letter counts for the window. Add the entering letter, remove the leaving letter, and compare the 26 counts with p's counts at each step. Each step is O(26) = O(1), giving O(n) overall instead of sorting every window.

Full answer

Problem

Given strings s and p (lowercase letters), return all indices i such that s[i:i + len(p)] is an anagram of p.

Example: s = "cbaebabacd", p = "abc" gives [0, 6] ("cba" and "bac").

Constraints: 1 <= len(s), len(p) <= 3 x 10^4.

Brute force

For each start, sort the window and compare with sorted p: O(n x m log m) for n = len(s), m = len(p).

Optimal approach

  1. Count letters of p in need[26].
  2. Slide over s, adding s[i] to have[26]. Once i >= m, subtract s[i - m], the letter that just left.
  3. When have == need, record i - m + 1.

Why it works

Two strings of equal length are anagrams exactly when their letter counts match. The window always has length m after the first m steps, and the counts are updated incrementally, so each comparison checks precisely the current window.

An optimisation keeps a single counter of how many letters currently match (matches from 0 to 26) and updates it in O(1) per step instead of comparing arrays; useful for large alphabets.

Complexity

O(n x 26) = O(n) time, O(1) space (two arrays of 26).

Code

python
def find_anagrams(s, p):
    """Start indices of every anagram of p in s. Fixed window with counts, O(len(s))."""
    if len(p) > len(s):
        return []
    need = [0] * 26
    have = [0] * 26
    for ch in p:
        need[ord(ch) - 97] += 1
    result = []
    for i, ch in enumerate(s):
        have[ord(ch) - 97] += 1
        if i >= len(p):
            have[ord(s[i - len(p)]) - 97] -= 1    # character leaving the window
        if have == need:                           # 26 comparisons: O(1)
            result.append(i - len(p) + 1)
    return result


def brute(s, p):
    k = len(p)
    return [i for i in range(len(s) - k + 1) if sorted(s[i:i + k]) == sorted(p)]


if __name__ == "__main__":
    for f in (find_anagrams, brute):
        assert f("cbaebabacd", "abc") == [0, 6]
        assert f("abab", "ab") == [0, 1, 2]
        assert f("a", "ab") == []
        assert f("aaaa", "a") == [0, 1, 2, 3]
        assert f("xyz", "abc") == []
    print("all tests passed")

Save as a23_find_anagrams.py and run python3 a23_find_anagrams.py. It prints all tests passed (Python 3.13.5).

Edge cases

p longer than s returns []. Overlapping answers ("abab", "ab" gives [0, 1, 2]). Single-character pattern. No matches. Uppercase or non-ASCII input needs a dictionary instead of a 26-slot array.

Pattern

Fixed-size sliding window with a frequency map. Closely related: permutation in string (return as soon as a match appears), and minimum window substring (variable size, "at least" counts).

python
def find_anagrams(s, p):
    """Start indices of every anagram of p in s. Fixed window with counts, O(len(s))."""
    if len(p) > len(s):
        return []
    need = [0] * 26
    have = [0] * 26
    for ch in p:
        need[ord(ch) - 97] += 1
    result = []
    for i, ch in enumerate(s):
        have[ord(ch) - 97] += 1
        if i >= len(p):
            have[ord(s[i - len(p)]) - 97] -= 1    # character leaving the window
        if have == need:                           # 26 comparisons: O(1)
            result.append(i - len(p) + 1)
    return result


def brute(s, p):
    k = len(p)
    return [i for i in range(len(s) - k + 1) if sorted(s[i:i + k]) == sorted(p)]


if __name__ == "__main__":
    for f in (find_anagrams, brute):
        assert f("cbaebabacd", "abc") == [0, 6]
        assert f("abab", "ab") == [0, 1, 2]
        assert f("a", "ab") == []
        assert f("aaaa", "a") == [0, 1, 2, 3]
        assert f("xyz", "abc") == []
    print("all tests passed")

Two 26-slot count arrays compared in O(1) per step; a brute force with sorting is checked on the same tests.

Complexity

Time: O(n), with a constant factor of 26. Space: O(1). For large alphabets, track the number of matching counts to avoid comparing whole arrays.

By level

Fresher: Uses count arrays and a fixed window, and explains add and remove on the example. Should test a pattern longer than the text.

Mid: Implements cleanly, explains the O(1) comparison and handles overlapping results and edge cases. Explains the matches counter optimisation.

Senior: Optimises with a match counter for large alphabets and relates the method to rolling hashes and other fixed-window matching problems. Can explain how the method changes for uppercase letters or Unicode text.

Key points

  • Anagram of p = same letter counts
  • Window length is fixed at len(p)
  • Add the entering letter and remove the leaving one
  • Compare 26 counts in O(1)
  • Overlapping matches are all reported

Common mistakes

  • Sorting every window
  • Removing the wrong index when the window slides
  • Starting comparisons before the window is full
  • Assuming lowercase letters without stating it

Follow-ups

  • How would you return just whether any permutation exists?
  • How would you handle a large alphabet efficiently?
  • How does minimum window substring differ?

Tips

  • Say "same counts" before code
  • Trace the window on the example
  • Mention the matches-counter optimisation

Evaluation rubric

  • Correct O(n) sliding window
  • Correct handling of window boundaries
  • Handles p longer than s
  • Correct complexity