Ebay Coding Interview Question: Find the First Anagram Substring Index

12 Views
No Comments

Problem Statement

Given two strings A and B, return the 0-based starting index of the first contiguous substring in A that is a permutation (anagram) of B.

If no such substring exists, return -1.

Constraints

  • 1 <= length of B <= length of A <= 100,000
  • A and B consist entirely of lowercase English letters.

Test Cases

Example 1

Input: A = "cbaebabacd", B = "abc"

Output: 0

Explanation: The substring "cba" starting at index 0 is a permutation of "abc".

This problem asks for the first 0-based index in A where a contiguous substring is an anagram of B, or -1 if none exists. Because the strings can be as long as 100,000 characters, the intended solution is a sliding window with frequency counting over the 26 lowercase letters. Track the character counts of B, slide a fixed-size window of length |B| across A, and check whether the window frequencies match the target. In the example A = "cbaebabacd" and B = "abc", the first window "cba" already matches, so the answer is 0.

END
 0