FastPrepFind the First Anagram Start Index

Find the First Anagram Start Index

Meta logoMeta● MediumFULLTIMEPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Given strings s and p, return the smallest zero-based starting index of a substring of s that is an anagram of p. Return -1 if no such substring exists.

An anagram has exactly the same character counts as p, so each candidate window has length p.length. Overlapping windows are valid candidates, and repeated letters must match with the same multiplicities. If several windows match, return only the first start.

Function

findAnagramStart(s: String, p: String) → int

Examples

Example 1

s = "cbaebabacd"p = "abc"return = 0

The first length-three anagram window is cba, starting at index zero.

Example 2

s = "zzbacxxabc"p = "abc"return = 2

The first matching window is bac at index two; a later match does not change the answer.

Example 3

s = "a"p = "ab"return = -1

The pattern is longer than the text, so no complete window exists.

Constraints

  • 1 <= s.length, p.length <= 10^4.
  • Both strings contain only lowercase English letters.

More Meta problems

See Meta hiring insights
public int findAnagramStart(String s, String p) {
    // Write your solution here.
}
s"cbaebabacd"
p"abc"
expected0
Checking account…