AceYourInterviews
Checking sign-in…

24. Find All Anagrams in a String

IntermediateFixed-size difference window with overlapping output

Find every place where a contiguous part of the text contains exactly the same letter counts as the pattern. Return the starting positions of all such substrings.

Matches may overlap, and repeated letters in the pattern must be matched with the same multiplicity. Follow the contract's index and output-order conventions.

Example 1

Input

text="cbaebabacd", pattern="abc"

Output

[0,6]

Explanation: cba and bac have the required three multiplicities.

Example 2

Input

text="aaaa", pattern="aa"

Output

[0,1,2]

Explanation: Overlapping windows are separate valid matches.

Constraints

  • 0 <= pattern.length, text.length <= 105
  • Both strings contain only lowercase English letters a–z. An empty pattern is permitted.
Hints
Hint 1

Turn the existence test into a predicate at every complete window.

Hint 2

Do matching windows permit skipping the next start?

Hint 3

Append matching starts and keep moving one position at a time.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Emit both separated matches

"cbaebabacd"
"abc"
[0,6]