FastPrepFastPrep
Problem Brief

Find First Anagram Index

FULLTIMEPHONE SCREEN

You are given two strings s and pattern. Find the starting index of the first substring of s that is an anagram of pattern.

If no substring of s is an anagram of pattern, return -1.

Two strings are anagrams if they contain the same characters with the same frequencies.

Function Description

Complete the function findFirstAnagramIndex in the editor below.

findFirstAnagramIndex has the following parameters:

  1. String s: the search string
  2. String pattern: the target anagram pattern

Returns

int: the starting index of the first anagram, or -1 if none exists.

1Example 1

Input
s = "cbaebabacd", pattern = "abc"
Output
0
Explanation

The substring "cba" starting at index 0 is an anagram of "abc", and it is the first such substring.

2Example 2

Input
s = "abab", pattern = "ab"
Output
0
Explanation

The substring "ab" starting at index 0 is already an anagram of the pattern, so the first valid index is 0.

Constraints

Limits and guarantees your solution can rely on.

The source thread did not provide explicit numeric bounds.

  • The anagram must be formed by a contiguous substring of s.
  • If multiple answers exist, return the smallest starting index.
public int findFirstAnagramIndex(String s, String pattern) {
    // write your code here
}
Input

s

"cbaebabacd"

pattern

"abc"

Output

0

Sign in to submit your solution.