Find All Anagrams in a String
Collect the starting indices of every substring that forms an anagram of pattern p using a sliding window frequency counter.
01The 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 | Why |
|---|---|---|
s = "cbaebabacd", p = "abc" | [0, 6] | Substrings "cba" at index 0 and "bac" at index 6 are anagrams of "abc" |
s = "abab", p = "ab" | [0, 1, 2] | Overlapping substrings: "ab" (0), "ba" (1), "ab" (2) |
s = "aaaa", p = "a" | [0, 1, 2, 3] | Every single character matches |
s = "a", p = "ab" | [] | p is longer than s |
Constraints: 1 to 30,000 characters, lowercase English letters only.
Loading the rest of the lesson…