Find All Anagrams in a String

Medium

Description

Given strings s and p, return start indices of p's anagrams in s. Use sliding window with character frequency comparison.

Examples

Input:s = "cbaebabacd", p = "abc"
Output:[0,6]
Explanation:

Anagrams of 'abc' start at index 0 ('cba') and 6 ('bac').

Input:s = "aabbccdd", p = "abcd"
Output:[1,2,3,4]
Explanation:

Anagrams of 'abcd' start at index 1 ('abbc'), 2 ('bbcc'), 3 ('bccd'), and 4 ('ccdd'). Each 4-character window contains exactly one 'a', one 'b', one 'c', and one 'd'.

Input:s = "aaaa", p = "aa"
Output:[0,1,2]
Explanation:

Anagrams of 'aa' start at index 0 ('aa'), 1 ('aa'), and 2 ('aa'). This demonstrates finding anagrams when the pattern contains repeated characters and all characters in the string are the same.

Constraints

  • 1 ≤ s.length, p.length ≤ 3 * 10⁴

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!