Find All Anagrams in a String (LeetCode 438): Solution and Explanation
Given two lowercase strings s and p, return every starting index in s where a substring of length len(p) is an anagram of p. An anagram uses exactly the same letters with the same counts, in any order. The indices can be returned in any order.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force way is to take every substring of s with the length of p, sort it or count its letters, and compare with p. Counting from scratch for each of the n windows costs O(n × m), where m is the length of p, and much of that work is repeated, because neighboring windows share all but two characters.
Since anagrams only care about letter counts, keep a 26-entry count array for p and another for the current window of s. When the window slides one step right, a single letter enters and a single letter leaves, so only two entries of the window's counts change. Comparing the two arrays in full at every step would be O(26) per slide, which is fine, but you can do better with very little extra code.
Track matches, the number of the 26 letters whose counts currently agree. Updating a count can only change whether that one letter agrees. If the count just became equal to the target, add one; if it was equal and now differs by one, subtract one. A window is an anagram exactly when matches equals 26, so each slide costs constant time and the whole scan is linear.
Approach: Fixed sliding window with a matches counter
- If
sis shorter thanp, return an empty list. - Count the letters of
pand of the firstlen(p)characters ofsinto two 26-entry arrays. - Compute
matchesas the number of letters whose two counts are equal. - For each window start
i, recordiifmatches == 26, then slide: adds[i + len(p)]and removes[i]. - After each count change, increment
matchesif that letter's count now equals thepcount, or decrement it if the letter just moved one away from equal. - After the loop, check the final window starting at
len(s) - len(p)and record it ifmatches == 26.
Step-by-step example
s = "cbaebabacd", p = "abc"
- The first window is "cba", which has the same counts as "abc", so
matchesstarts at 26. - At i = 0,
matchesis 26, so index 0 is recorded. Sliding adds e and removes c, which breaks two letters, andmatchesdrops to 24. - The windows "bae", "aeb", "eba", "bab" and "aba" all keep
matchesat 24, so nothing is recorded for starts 1 through 5. - Sliding from "aba" to "bac" adds c, which fixes c, and removes a, which fixes a, so
matchesreturns to 26. - At i = 6, index 6 is recorded. The final slide to "acd" drops
matchesto 24, so the last window is not added. - The result is [0, 6].
Code: Python, Java, C++
1class Solution:
2 def findAnagrams(self, s: str, p: str) -> List[int]:
3 result = []
4 if len(s) < len(p):
5 return result
6 p_count = [0] * 26
7 s_count = [0] * 26
8 for i in range(len(p)):
9 p_count[ord(p[i]) - ord('a')] += 1
10 s_count[ord(s[i]) - ord('a')] += 1
11 matches = sum(1 for i in range(26) if p_count[i] == s_count[i])
12 for i in range(len(s) - len(p)):
13 if matches == 26:
14 result.append(i)
15 left = ord(s[i]) - ord('a')
16 right = ord(s[i + len(p)]) - ord('a')
17 s_count[right] += 1
18 if s_count[right] == p_count[right]:
19 matches += 1
20 elif s_count[right] == p_count[right] + 1:
21 matches -= 1
22 s_count[left] -= 1
23 if s_count[left] == p_count[left]:
24 matches += 1
25 elif s_count[left] == p_count[left] - 1:
26 matches -= 1
27 if matches == 26:
28 result.append(len(s) - len(p))
29 return result1class Solution {
2 public List<Integer> findAnagrams(String s, String p) {
3 List<Integer> result = new ArrayList<>();
4 if (s.length() < p.length()) return result;
5 int[] pCount = new int[26];
6 int[] sCount = new int[26];
7 for (int i = 0; i < p.length(); i++) {
8 pCount[p.charAt(i) - 'a']++;
9 sCount[s.charAt(i) - 'a']++;
10 }
11 int matches = 0;
12 for (int i = 0; i < 26; i++) {
13 if (pCount[i] == sCount[i]) matches++;
14 }
15 for (int i = 0; i < s.length() - p.length(); i++) {
16 if (matches == 26) result.add(i);
17 int left = s.charAt(i) - 'a';
18 int right = s.charAt(i + p.length()) - 'a';
19 sCount[right]++;
20 if (sCount[right] == pCount[right]) matches++;
21 else if (sCount[right] == pCount[right] + 1) matches--;
22 sCount[left]--;
23 if (sCount[left] == pCount[left]) matches++;
24 else if (sCount[left] == pCount[left] - 1) matches--;
25 }
26 if (matches == 26) result.add(s.length() - p.length());
27 return result;
28 }
29}1class Solution {
2public:
3 vector<int> findAnagrams(string s, string p) {
4 vector<int> result;
5 if (s.length() < p.length()) return result;
6 vector<int> pCount(26, 0), sCount(26, 0);
7 for (int i = 0; i < p.length(); i++) {
8 pCount[p[i] - 'a']++;
9 sCount[s[i] - 'a']++;
10 }
11 int matches = 0;
12 for (int i = 0; i < 26; i++) {
13 if (pCount[i] == sCount[i]) matches++;
14 }
15 for (int i = 0; i < s.length() - p.length(); i++) {
16 if (matches == 26) result.push_back(i);
17 int left = s[i] - 'a';
18 int right = s[i + p.length()] - 'a';
19 sCount[right]++;
20 if (sCount[right] == pCount[right]) matches++;
21 else if (sCount[right] == pCount[right] + 1) matches--;
22 sCount[left]--;
23 if (sCount[left] == pCount[left]) matches++;
24 else if (sCount[left] == pCount[left] - 1) matches--;
25 }
26 if (matches == 26) result.push_back(s.length() - p.length());
27 return result;
28 }
29};Time and space complexity
O(n)
Here n is the length of s. Building the initial counts takes O(m + 26) and each of the remaining slides updates two counts and matches in constant time.
O(1)
The two count arrays always have 26 entries. The output list is not counted as extra space.
Other approaches
Compare count arrays directly (time O(26 × n), space O(1))
Slide the window and compare s_count == p_count at each step. It is shorter and still linear, with a constant factor of 26 per position, which is usually fast enough.
Hash map of counts with a need counter (time O(n), space O(k))
Store the needed counts of p in a hash map and track how many characters are still missing as the window moves. This generalizes to larger alphabets such as Unicode, where a fixed 26-entry array does not fit.
Common mistakes
- Forgetting to check the final window after the loop, since the loop records a start before it slides and never sees the last position.
- Adjusting
matcheson every count change instead of only when a letter's agreement flips, which quickly makes the counter meaningless. - Sorting each window, which turns a linear problem into O(n × m log m).
- Not guarding against
len(s) < len(p), which causes an index error when building the first window.
Frequently asked questions
How do you find all anagrams of a pattern in a string?
Slide a window of the pattern's length across the string and keep letter counts for the window. Whenever the counts equal the pattern's counts, the window's starting index is an answer.
What is the time complexity of Find All Anagrams in a String?
It is O(n), where n is the length of s, because each slide changes two counts in constant time. Space is O(1) for the fixed alphabet.
How is this different from Permutation in String?
The technique is identical. Permutation in String stops and returns True at the first matching window, while this problem collects every starting index where a match occurs.