Find All Anagrams in a String
Find All Anagrams in a String is LeetCode 438 (Medium). Given two strings s and p, return the start index of every substring of s that is an anagram of p: the same letters, each used the same number of times, in any order. The indices may be returned in any order.
- Both strings hold only lowercase letters, so a letter count fits in 26 slots.
- Each string can be 30,000 letters long, so sorting or recounting every substring is too slow.
- 1 <= s.length, p.length <= 3 * 10⁴
- s and p consist of lowercase English letters.
Intuition
An anagram of p has exactly len(p) letters, so only substrings of that length can match. Two substrings next to each other share all but one letter at each end. Keep one letter count for the current window and change it by one letter in and one letter out, instead of counting the whole substring again.
The window is an anagram exactly when its 26 counts equal the 26 counts of p. Letter order never matters, so the counts alone decide it, and comparing two arrays of 26 numbers takes the same small time whatever the length of p.
"Find every substring of length k with some property of its letters" is a fixed-size sliding window: the window length never changes, so each step adds one letter and removes one. When the property is "same letters as p", the window keeps a letter count.
Approach
Before reading on, write how the letter count changes when the window moves one step right. Then decide when the first full window exists, and which index you record when a window matches. Aim for O(n) time and O(1) extra space.
Two ways to solve it
Keep a 26-slot count for the window and compare it with the count for p after every step.
- Simple: one comparison decides each window.
- Cost: 26 checks per step, still linear.
Keep one number: how many letters of p the window still lacks. A window matches when that number is 0.
- Faster per step: no 26-slot comparison.
- Care: the number changes only when a count crosses 0.
Both slide a window of len(p) letters in O(n) time and O(1) extra space. The steps, code and live demo follow the count comparison; the second version's code comes after the demo.
Count the letters of p
Fill need, an array of 26 zeros, with one count per letter of p. Any window that matches must hold exactly these counts, so this array never changes.
Add the letter that enters
Move right across s and add 1 to window for s[right]. Before the window reaches len(p) letters its counts add up to fewer letters than need holds, so it cannot match yet.
Remove the letter that leaves
Once right is at least len(p), take 1 off the count of s[right - len(p)]. That letter has just fallen out of the left end, so the window again holds exactly len(p) letters.
Compare the counts and record the start
If window equals need, the window is an anagram, and it starts at right - len(p) + 1. Record that index. Overlapping matches are all kept, because the window moves one step at a time and never jumps past a match.
Code in Python, C++ and Java
abc. Any window of 3 letters whose counts equal that row is an anagram, whatever the order of its letters.abc yet.abc yet.abc, so cba is an anagram. Record where it starts, index 0, not where it ends.bae has 0 'c' but abc has 1. One different count is enough to rule it out.aeb has 0 'c' but abc has 1. One different count is enough to rule it out.eba has 0 'c' but abc has 1. One different count is enough to rule it out.bab has 2 'b' but abc has 1. One different count is enough to rule it out.aba has 2 'a' but abc has 1. One different count is enough to rule it out.abc, so bac is an anagram. Record where it starts, index 6, not where it ends.acd has 0 'b' but abc has 1. One different count is enough to rule it out.ab. Any window of 2 letters whose counts equal that row is an anagram, whatever the order of its letters.ab yet.ab, so ab is an anagram. Record where it starts, index 0, not where it ends.ab, so ba is an anagram. Record where it starts, index 1, not where it ends.ab, so ab is an anagram. Record where it starts, index 2, not where it ends.abb. Any window of 3 letters whose counts equal that row is an anagram, whatever the order of its letters.abb yet.abb yet.aab has 2 'a' but abb has 1. One different count is enough to rule it out.abb. The answer is empty.Track how many letters are still missing
need starts as the counts of p and missing as len(p). A letter that enters while its count is still positive was needed, so missing drops by 1; a letter that leaves and pushes its count back above 0 is needed again, so missing rises by 1. A full window with missing == 0 holds exactly the letters of p.
Common pitfalls
Recording the right end instead of the start
if window == need:
answer.append(right)if window == need:
answer.append(right - k + 1)The question asks where each anagram begins. On s = "cbaebabacd", p = "abc" the matches end at indices 2 and 8, but the expected answer is [0, 6].
Removing the leaving letter one step too early
if right >= k - 1:
window[ord(s[right - k + 1]) - 97] -= 1if right >= k:
window[ord(s[right - k]) - 97] -= 1The letter at right - k + 1 is the first letter of the current window, not one that has left. Removing it leaves only k - 1 letters, so no window can ever match: s = "ab", p = "ab" returns [] instead of [0].
Edge cases
p is longer than sThe window never holds len(p) letters, so its counts never add up to those of p and the answer stays empty. No separate check is needed, as in s = "ab", p = "abc".
p repeats a letterThe count for that letter is 2 or more, and the window must hold that letter the same number of times. For s = "aab", p = "abb" the only window holds two a's and one b, so nothing matches.
Complexity
s enters and leaves the window once, and each comparison checks 26 slots, so the work is about 26 · n steps. The two count arrays have 26 slots whatever the input size; the answer list is not counted.Find All Anagrams in a String FAQ
How is this different from Permutation in String?
Permutation in String (LeetCode 567) asks only whether some window of s matches, so it can stop at the first match and return true. Here every match is wanted, so the window runs to the end of s and records each start index.
Why not sort each substring and compare it with sorted p?
It gives the right answer, but sorting a substring of length m costs about m log m, and there are up to n of them. With both strings at 30,000 letters, that is billions of steps. The sliding count spends a fixed 26 checks per position instead.
Does the same code work for Unicode or uppercase letters?
Not as written: ord(ch) - 97 assumes the 26 lowercase letters. For a larger alphabet, use a hash map from letter to count, and with the missing-letter count only the letters of p need entries.