Find All Anagrams in a String - Problem

Imagine you're a word detective searching for hidden anagrams within a larger string! Given two strings s (the haystack) and p (the needle), your mission is to find all starting positions where anagrams of p appear as substrings in s.

What's an anagram? It's a rearrangement of letters - like "abc" and "bca" are anagrams because they contain the same letters with the same frequency.

Example: If s = "abab" and p = "ab", then positions 0 and 2 contain anagrams of "ab" ("ab" at index 0 and "ab" at index 2).

Return an array of all the starting indices where p's anagrams begin in s. The order of results doesn't matter!

Input & Output

example_1.py — Python
$ Input: s = "abab", p = "ab"
Output: [0, 2]
💡 Note: The substring "ab" at index 0 is an anagram of "ab". The substring "ab" at index 2 is an anagram of "ab".
example_2.py — Python
$ Input: s = "cbaebabacd", p = "abc"
Output: [1, 6]
💡 Note: The substring "bae" at index 1 is an anagram of "abc" (contains a,b,c). The substring "bac" at index 6 is an anagram of "abc".
example_3.py — Python
$ Input: s = "abacabad", p = "aaab"
Output: []
💡 Note: No substring of length 4 in s contains exactly 3 'a's and 1 'b', so no anagrams exist.

Visualization

Tap to expand
String: "cbaebabacd" | Pattern: "abc"cbaebabacdWindow: "eba"Target "abc" Frequenciesa: 1b: 1c: 1✓ Total: 3 charsCurrent "eba" Frequenciesa: 1b: 1e: 1❌ Missing 'c', has 'e'Slide Window →Matches Found at Indices: [1, 6] 🎯
Understanding the Visualization
1
Setup Phase
Create frequency map for target pattern and initialize first window
2
Check Current Window
Compare frequency maps to detect anagram
3
Slide Window Right
Remove leftmost character and add new rightmost character
4
Update Frequencies
Efficiently update frequency counts and check for new matches
Key Takeaway
🎯 Key Insight: The sliding window technique transforms an O(n×m×log m) brute force solution into an elegant O(n+m) algorithm by maintaining frequency counts as we slide, rather than recalculating everything from scratch each time.

Time & Space Complexity

Time Complexity
⏱️
O(n + m)

Single pass through string s (n) plus creating frequency map for p (m)

n
2n
Linear Growth
Space Complexity
O(1)

Hash maps store at most 26 characters (constant space for lowercase English letters)

n
2n
Linear Space

Constraints

  • 1 ≤ s.length, p.length ≤ 3 × 104
  • s and p consist of lowercase English letters only
  • Both strings are non-empty
Asked in
Amazon 45 Google 38 Facebook 32 Microsoft 28
87.4K Views
High Frequency
~18 min Avg. Time
1.8K 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