LeetCode #438 Medium

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.
Constraints
  • 1 <= s.length, p.length <= 3 * 10⁴
  • s and p consist of lowercase English letters.
stringsliding-windowhash-table
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def findAnagrams(self, s: str, p: str) -> List[int]:
▶6 k = len(p)
▶7 need = [0] * 26
▶8 window = [0] * 26
▶9 for ch in p:
▶10 need[ord(ch) - 97] += 1
▶11 answer = []
▶12 for right, ch in enumerate(s):
▶13 window[ord(ch) - 97] += 1
▶14 if right >= k:
▶15 window[ord(s[right - k]) - 97] -= 1
▶16 if window == need:
▶17 answer.append(right - k + 1)
▶18 return answer
c0b1a2e3b4a5b6a7c8d9p needswindowa10b10c10d00e00answercount p: the window must hold the same letters
pabc
window size3
The top row of counts is the letters of abc. Any window of 3 letters whose counts equal that row is an anagram, whatever the order of its letters.
c0inb1a2e3b4a5b6a7c8d9p needswindowa10b10c11d00e00answer'c' enters → 1 of 3 letters, not full yet
right0
'c' in window1
Add 1 to the count of 'c'. The window holds only 1 letter and an anagram needs 3, so its counts cannot equal those of abc yet.
c0b1ina2e3b4a5b6a7c8d9p needswindowa10b11c11d00e00answer'b' enters → 2 of 3 letters, not full yet
right1
'b' in window1
Add 1 to the count of 'b'. The window holds only 2 letters and an anagram needs 3, so its counts cannot equal those of abc yet.
c0b1a2ine3b4a5b6a7c8d9p needswindowa11b11c11d00e00answer0'a' enters → counts match → anagram starts at 0
windowcba
start0
Add 1 to the count of 'a'. The first full window of 3 letters is ready. Every letter count of the window equals the count in abc, so cba is an anagram. Record where it starts, index 0, not where it ends.
c0b1a2e3inb4a5b6a7c8d9p needswindowa11b11c11d00e01answer0'e' enters → 4 letters, one too many
right3
'e' in window1
Add 1 to the count of 'e'. The window now spans 4 letters, from index 0 to 3, so the letter at its left end has to go before the counts are compared.
c0outb1a2e3b4a5b6a7c8d9p needswindowa11b11c10d00e01answer0'c' leaves → 0 'c', p needs 1 → no match
windowbae
'c'0 vs 1
Take 1 off the count of 'c', the letter at index 0. The window is back to 3 letters. The window bae has 0 'c' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4ina5b6a7c8d9p needswindowa11b12c10d00e01answer0'b' enters → 4 letters, one too many
right4
'b' in window2
Add 1 to the count of 'b'. The window now spans 4 letters, from index 1 to 4, so the letter at its left end has to go before the counts are compared.
c0b1outa2e3b4a5b6a7c8d9p needswindowa11b11c10d00e01answer0'b' leaves → 0 'c', p needs 1 → no match
windowaeb
'c'0 vs 1
Take 1 off the count of 'b', the letter at index 1. The window is back to 3 letters. The window aeb has 0 'c' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4a5inb6a7c8d9p needswindowa12b11c10d00e01answer0'a' enters → 4 letters, one too many
right5
'a' in window2
Add 1 to the count of 'a'. The window now spans 4 letters, from index 2 to 5, so the letter at its left end has to go before the counts are compared.
c0b1a2oute3b4a5b6a7c8d9p needswindowa11b11c10d00e01answer0'a' leaves → 0 'c', p needs 1 → no match
windoweba
'c'0 vs 1
Take 1 off the count of 'a', the letter at index 2. The window is back to 3 letters. The window eba has 0 'c' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4a5b6ina7c8d9p needswindowa11b12c10d00e01answer0'b' enters → 4 letters, one too many
right6
'b' in window2
Add 1 to the count of 'b'. The window now spans 4 letters, from index 3 to 6, so the letter at its left end has to go before the counts are compared.
c0b1a2e3outb4a5b6a7c8d9p needswindowa11b12c10d00e00answer0'e' leaves → 2 'b', p needs 1 → no match
windowbab
'b'2 vs 1
Take 1 off the count of 'e', the letter at index 3. The window is back to 3 letters. The window bab has 2 'b' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4a5b6a7inc8d9p needswindowa12b12c10d00e00answer0'a' enters → 4 letters, one too many
right7
'a' in window2
Add 1 to the count of 'a'. The window now spans 4 letters, from index 4 to 7, so the letter at its left end has to go before the counts are compared.
c0b1a2e3b4outa5b6a7c8d9p needswindowa12b11c10d00e00answer0'b' leaves → 2 'a', p needs 1 → no match
windowaba
'a'2 vs 1
Take 1 off the count of 'b', the letter at index 4. The window is back to 3 letters. The window aba has 2 'a' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4a5b6a7c8ind9p needswindowa12b11c11d00e00answer0'c' enters → 4 letters, one too many
right8
'c' in window1
Add 1 to the count of 'c'. The window now spans 4 letters, from index 5 to 8, so the letter at its left end has to go before the counts are compared.
c0b1a2e3b4a5outb6a7c8d9p needswindowa11b11c11d00e00answer06'a' leaves → counts match → anagram starts at 6
windowbac
start6
Take 1 off the count of 'a', the letter at index 5. The window is back to 3 letters. Every letter count of the window equals the count in abc, so bac is an anagram. Record where it starts, index 6, not where it ends.
c0b1a2e3b4a5b6a7c8d9inp needswindowa11b11c11d01e00answer06'd' enters → 4 letters, one too many
right9
'd' in window1
Add 1 to the count of 'd'. The window now spans 4 letters, from index 6 to 9, so the letter at its left end has to go before the counts are compared.
c0b1a2e3b4a5b6outa7c8d9p needswindowa11b10c11d01e00answer06'b' leaves → 0 'b', p needs 1 → no match
windowacd
'b'0 vs 1
Take 1 off the count of 'b', the letter at index 6. The window is back to 3 letters. The window acd has 0 'b' but abc has 1. One different count is enough to rule it out.
c0b1a2e3b4a5b6a7c8d9p needswindowa11b10c11d01e00answer06answer: starts 0, 6
answer[0, 6]
Every window of 3 letters was checked exactly once, each by changing two counts and comparing. The anagrams start at 0, 6.
05

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.

▶1from typing import List
▶2 
▶3 
▶4class Solution:
▶5 def findAnagrams(self, s: str, p: str) -> List[int]:
▶6 k = len(p)
▶7 need = [0] * 26
▶8 for ch in p:
▶9 need[ord(ch) - 97] += 1
▶10 missing = k
▶11 answer = []
▶12 for right, ch in enumerate(s):
▶13 c = ord(ch) - 97
▶14 if need[c] > 0:
▶15 missing -= 1
▶16 need[c] -= 1
▶17 if right >= k:
▶18 c = ord(s[right - k]) - 97
▶19 need[c] += 1
▶20 if need[c] > 0:
▶21 missing += 1
▶22 if missing == 0:
▶23 answer.append(right - k + 1)
▶24 return answer
06

Common pitfalls

Recording the right end instead of the start

✗ Wrong
if window == need:
    answer.append(right)
✓ 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

✗ Wrong
if right >= k - 1:
    window[ord(s[right - k + 1]) - 97] -= 1
✓ Right
if right >= k:
    window[ord(s[right - k]) - 97] -= 1

The 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].

07

Edge cases

p is longer than s

The 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 letter

The 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.

08

Complexity

Time
O(n)
Space
O(1)
Each letter of 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.
09

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.