Skip to main content

438. Find All Anagrams in a String

https://leetcode.com/problems/find-all-anagrams-in-a-string/

Python

from collections import Counter


class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []

count_s, count_p = Counter(), Counter(p)

ans = []
for i in range(len(s)):
count_s[s[i]] += 1

# Reach end, move left (i-len(p)) forward
if i >= len(p):
if count_s[s[i-len(p)]] == 1:
del count_s[s[i-len(p)]]
else:
count_s[s[i-len(p)]] -= 1

# All counts are the same
if count_s == count_p:
ans.append(i-len(p)+1)

return ans