Problem · String
Find First Anagram Index
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.
Complete the function findFirstAnagramIndex in the editor below.
findFirstAnagramIndex has the following parameters:
String s: the search stringString pattern: the target anagram pattern
Returns
int: the starting index of the first anagram, or -1 if none exists.
Examples
01 · Example 1
s = "cbaebabacd" pattern = "abc" return = 0
The substring "cba" starting at index 0 is an anagram of "abc", and it is the first such substring.
02 · Example 2
s = "abab" pattern = "ab" return = 0
The substring "ab" starting at index 0 is already an anagram of the pattern, so the first valid index is 0.
Constraints
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.
More Databricks problems
- Fastest SF CommutePHONE SCREEN · Seen May 2026
- Minimize CommuteOA · Seen Apr 2026
- Difference Between Sums of PositionsSeen Sep 2024
- Longest Common Prefix of Number PairsSeen Sep 2024
- Subarray CountingSeen Sep 2024
- Write 'L' on MatrixSeen Sep 2024
- Binary String RequestsSeen Aug 2024
- Bounding Diagonal WeightsSeen Aug 2024
public int findFirstAnagramIndex(String s, String pattern) {
// write your code here
}
s"cbaebabacd"
pattern"abc"
expected0
sign in to submit