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,4,5,6]
💡 Note: The anagrams of "ab" in "cbaebabacd" start at indices 1 ("ba"), 4 ("ba"), 5 ("ab"), and 6 ("ba"). All of these substrings are anagrams of "ab".
Example 2 — Multiple Matches
$ Input: s = "abab", p = "ab"
Output: [0,1,2]
💡 Note: Anagrams start at indices 0 ("ab"), 1 ("ba"), and 2 ("ab"). All substrings of length 2 form anagrams of "ab".
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 in a String INPUT String s = "cbaebabacd" c 0 b 1 a 2 e 3 b 4 a 5 b 6 a 7 c 8 Pattern p = "ab" a b Anagrams of "ab": "ab" or "ba" Window Size = len(p) = 2 Slide window of size 2 over s Input Summary s = "cbaebabacd" p = "ab" ALGORITHM STEPS 1 Count Pattern Chars Build freq map for p a:1, b:1 p_count 2 Init Window First window s[0:2]="cb" c:1, b:1 window_count 3 Slide Window Compare counts each pos i=1: "ba" --> a:1,b:1 = p_count [OK] i=6: "ba" --> a:1,b:1 = p_count [OK] Others: counts don't match 4 Collect Results Store matching indices Time: O(n) | Space: O(1) Fixed 26 char alphabet FINAL RESULT Anagram positions found: Index 1: s[1:3] = "ba" b a = anagram Index 6: s[6:8] = "ba" b a = anagram OUTPUT [1, 6] OK - Verified! Both "ba" at indices 1 and 6 are anagrams of "ab" Key Insight: Sliding Window + Character Frequency: Instead of sorting each window O(k log k), use a fixed-size frequency array (26 letters). Compare window counts with pattern counts in O(1) time. Slide the window by removing left char and adding right char, maintaining counts efficiently. TutorialsPoint - Find All Anagrams in a String | Optimal Sliding Window Solution
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