Find All Anagrams in a String - Problem
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
Input & Output
Example 1 — Basic Case
$
Input:
s = "cbaebabacd", p = "ab"
›
Output:
[1,6]
💡 Note:
The anagrams of "ab" in "cbaebabacd" start at indices 1 ("ba") and 6 ("ab"). Both "ba" and "ab" are anagrams of "ab".
Example 2 — Multiple Matches
$
Input:
s = "abab", p = "ab"
›
Output:
[0,2]
💡 Note:
Anagrams start at indices 0 ("ab") and 2 ("ab"). Both substrings are exactly the pattern or valid anagrams.
Example 3 — No Matches
$
Input:
s = "xyz", p = "ab"
›
Output:
[]
💡 Note:
No substring of length 2 in "xyz" can form an anagram of "ab" since the characters don't match.
Constraints
- 1 ≤ s.length, p.length ≤ 3 × 104
- s and p consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s and pattern p to find anagrams of
2
Process
Slide window of size |p| and compare character frequencies
3
Output
Array of starting indices where anagrams are found
Key Takeaway
🎯 Key Insight: Anagrams have identical character frequencies - use sliding window to efficiently compare frequencies in O(n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code