Find All Anagrams in a String – Solution & Complexity
Solution Walkthrough
1. Look for fixed-size windows
- Every candidate substring must have exactly the same length as
p. - That makes this a sliding-window problem rather than a variable-size window like minimum cover.
2. Recount each window from scratch
- For every start index, build a fresh 26-letter frequency array for the substring and compare it with
p. - This is correct, but it repeats almost all of the counting work between neighboring windows.
3. Slide one fixed-size window across s
- Count
ponce, count the first window once, then update the window inO(1)per move. - Because the alphabet size is fixed at 26, comparing the two count arrays is still constant time.
4. Update counts incrementally
- Add the new right character, remove the old left character, and compare the arrays.
- Every window is visited exactly once.
5. Dry run / sliding-window trace
Trace s = "abab", p = "ab".
| window | indices | counts match? | answer |
|---|---|---|---|
"ab" | [0,1] | yes | [0] |
slide right -> "ba" | [1,2] | yes | [0,1] |
slide right -> "ab" | [2,3] | yes | [0,1,2] |
Only one character enters and one leaves on each step, so recomputing the full frequency table is unnecessary.
6. Final solution and complexity
A fixed-size sliding window with 26-letter frequency arrays finds every anagram in linear time and constant extra space.