class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
# time O(S+P) space O(1)
cntP = {}
cntS = {}
r = 0
res = []
for pp in p:
if pp not in cntP:
cntP[pp] = 1
else:
cntP[pp] += 1
# [l,r] is current window
for l in range(len(s)):
while r < len(s) and r - l +1 <= len(p):
if s[r] not in cntS:
cntS[s[r]] = 1
else:
cntS[s[r]] += 1
r += 1
if cntS == cntP:
res.append(l)
cntS[s[l]] -= 1
if cntS[s[l]] == 0 :
cntS.pop(s[l])
return res
Optimiazation: instead of dictionary, can use array of size 26