We use a sliding window of size len(p) and compare character counts. We can optimize by tracking the number of "matches" (character counts that are exactly equal).
- If
len(p) > len(s), return []. - Count frequencies of
pand the firstlen(p)chars ofs. - Slide the window:
- If window's
Counterequalsp'sCounter, add start index to result. - Update
Counterby adding one character from right and removing one from left.
- If window's
- Time Complexity: O(N).
- Space Complexity: O(1) (26 characters).
from collections import Counter
def find_anagrams(s, p):
res = []
ns, np = len(s), len(p)
if np > ns: return res
pCount = Counter(p)
sCount = Counter(s[:np])
if pCount == sCount:
res.append(0)
for i in range(1, ns - np + 1):
sCount[s[i-1]] -= 1
if sCount[s[i-1]] == 0:
del sCount[s[i-1]]
sCount[s[i+np-1]] += 1
if pCount == sCount:
res.append(i)
return res