Find All Anagrams in a String
1 approach, code in every language
Problem description
Given two strings s and p, report the starting index of every substring of s that is an anagram of p, meaning it uses exactly the same letters with the same multiplicities as p.
The indices can be returned in any order, and an empty list is valid when no such substring exists.
Example 1
Input: s = "cbaebabacd", p = "abc"
Output: [0, 6]
The substrings starting at index 0 ("cba") and index 6 ("bac") are rearrangements of "abc".
Example 2
Input: s = "abab", p = "ab"
Output: [0, 1, 2]
Each window "ab", "ba", and "ab" is an anagram of "ab".
Constraints
1 <= s.length, p.length <= 3 * 10^4s and p consist of lowercase English letters.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Mosaic Bundle Positions is our own problem on the technique behind Find All Anagrams in a String: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free