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
Find All Anagrams: Pattern Matching with Character FrequenciesInput: s = "cbaebabacd", p = "ab"cbaebabacd0123456789Pattern: "ab" (need a:1, b:1)baIndex 1 ✓abIndex 6 ✓Sliding window checks character frequenciesOutput: [1, 6]
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
Asked in
Facebook 35 Amazon 28 Google 22 Microsoft 18
487.2K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen