Problem Statement
Given a string s and a pattern string p, find all start indices of p's anagrams in s.
An anagram is a permutation of the characters — same character frequencies, different order.
Return the indices in any order.
Constraints
1 <= s.length, p.length <= 3 * 10^4sandpconsist of lowercase English letters only- Expected: O(n) time, O(1) space (since alphabet is fixed at 26)
Example
Input: s = "cbaebabacd", p = "abc"
Output: [0, 6]
Explanation:
- Index 0:
"cba"is an anagram of"abc" - Index 6:
"bac"is an anagram of"abc"
Input: s = "abab", p = "ab"
Output: [0, 1, 2]
What the Interviewer Expects
- Fixed-size sliding window — window size =
p.length. Slide acrosss. - Frequency map comparison — maintain character frequency of the current window. Compare with
p's frequency map. - Optimized comparison — instead of comparing full maps each time, maintain a
matchCountvariable. Increment/decrement as characters enter/leave the window. - O(n) time — each character is processed exactly twice (enter and leave window).
- Edge case:
plonger thans→ return empty array.
Follow-ups
- What if the alphabet is not limited to 26 characters (e.g., Unicode strings)?
- What if you need to find anagrams allowing at most K character substitutions?
- Can you solve this without a frequency map using XOR or hashing? What are the trade-offs?
- What if
pcontains wildcards that match any character?