FastPrepAll Anagram Start Indices

All Anagram Start Indices

Motive logoMotive● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given lowercase strings s and p, return every starting index where a substring of s is an anagram of p.

Return indices in increasing order. Overlapping matches are included.

Function

findAnagrams(s: String, p: String) → int[]

Examples

Example 1

s = "acbadabcaa"p = "aabc"return = [0,5,6]

The length-four substrings at 0, 5, and 6 have exactly the pattern frequencies.

Example 2

s = "cbaebabacd"p = "abc"return = [0,6]

cba and bac are anagrams of abc.

Example 3

s = "abab"p = "ab"return = [0,1,2]

All three length-two windows match, including overlaps.

Constraints

  • 1 ≤ s.length, p.length ≤ 100000.
  • s and p contain only lowercase English letters.

More Motive problems

See Motive hiring insights
public int[] findAnagrams(String s, String p) {
    // write your code here
}
s"acbadabcaa"
p"aabc"
expected[0,5,6]
Checking account…