Sliding Window · Fixed size

Find All Anagrams Visualizer

What is Find All Anagrams

Return every start index where the substring of s has the same letters, with the same counts, as p. The window length stays equal to the length of p.

cbaebabacd
abc
0 6

Approach

Sort every windowSorting each block of the pattern length repeats work that a count update can avoid.
Compare letter countsAdd the letter that enters and remove the letter that leaves. When the counts match the pattern, record the start index.

Interactive solution

Pattern above the window, matching starts collected
count the pattern
slide a window of that length
if the counts match, record the start
return the start indices
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.

Complexity

PieceCostWhy
TimeO(n)Each letter enters and leaves once. Comparing 26 counts is constant for lowercase letters.
MemoryO(1)Two small count tables.

Implementation

def find_anagrams(s, p):
    if len(p) > len(s):
        return []
    need, have, ans = {}, {}, []
    for ch in p:
        need[ch] = need.get(ch, 0) + 1
    for i, ch in enumerate(s):
        have[ch] = have.get(ch, 0) + 1
        if i >= len(p):
            old = s[i - len(p)]
            have[old] -= 1
            if have[old] == 0:
                del have[old]
        if i >= len(p) - 1 and have == need:
            ans.append(i - len(p) + 1)
    return ans