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
Interactive solution
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
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each letter enters and leaves once. Comparing 26 counts is constant for lowercase letters. |
| Memory | O(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