Find All Anagrams In A String Problem
Description
LeetCode Problem 438.
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Example 1:
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
Constraints:
- 1 <= s.length, p.length <= 3 * 10^4
- s and p consist of lowercase English letters.
Solution
Approach: Fixed-Size Sliding Window
Two strings are anagrams exactly when they contain each letter the same number of times. So we need to know, for every substring of s with length len(p), whether its letter counts equal those of p. Counting each substring from scratch costs O(len(p)) per position; a sliding window updates the counts in O(1) instead.
- Count the letters of
pin an arrayp_countof size 26. - Walk through
swith indexi. Adds[i]towindow_count. Oncei >= len(p), the window is one letter too long, so removes[i - len(p)]. - Now
window_countdescribess[i - len(p) + 1 .. i]. If it equalsp_count, record the start indexi - len(p) + 1.
Comparing two arrays of 26 counts takes constant time, so each step is O(1).
The detail to get right is the window bounds: a match can only happen once the window holds a full len(p) letters. Before that, the window has fewer letters than p and its counts add up to less than len(p) and cannot match, so no extra check is needed. If p is longer than s, return an empty list right away.
Complexity: O(n) time, where n is the length of s (each step does a constant 26-entry comparison), plus O(m) to count p of length m. O(1) extra space besides the answer.
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s):
return []
p_count = [0] * 26
window_count = [0] * 26 # letter counts of s[i - len(p) + 1 .. i]
for c in p:
p_count[ord(c) - ord("a")] += 1
answer = []
for i, c in enumerate(s):
window_count[ord(c) - ord("a")] += 1 # letter entering the window
if i >= len(p):
window_count[ord(s[i - len(p)]) - ord("a")] -= 1 # letter leaving the window
if window_count == p_count:
answer.append(i - len(p) + 1) # start of the current window
return answer
Now write it from memory
Close the write-up and solve it yourself against the tests.