Find All Anagrams in a String
medium
strings
sliding-window
hashmap
Given two lowercase strings s and p, return every start index of a substring in s that is an anagram of p.
Return the indices in ascending order.
Input / output
- Input:
s: string,p: string - Output:
int[]of start indices
Examples
s = "cbaebabacd",p = "abc"returns[0, 6].s = "abab",p = "ab"returns[0, 1, 2].s = "af",p = "be"returns[].
Constraints
1 <= p.length <= s.length <= 30000sandpcontain only lowercase English letters.
Edge cases
- Repeated letters in
pmatter. - Overlapping anagrams should all be reported.
- The answer may be empty.
Target complexity
- Aim for
O(|s|)time andO(1)extra space beyond the output.
Hints
- Because only lowercase English letters appear, a 26-length count array is enough.
- Slide a window of length
p.length, adding one new character and removing one old character each step.
Follow-up
How would your approach change if s and p could contain arbitrary Unicode characters instead of only lowercase English letters?
Examples
Example 1
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Example 2
Input: s = "abab", p = "ab"
Output: [0,1,2]
Example 3
Input: s = "af", p = "be"
Output: []
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.