Earliest Substring That Is a Rearrangement of a Pattern
Company: Databricks
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Find the starting index of the first substring of a text that is a rearrangement of a given pattern, or report that none exists. Tests fixed-length sliding windows, character-frequency bookkeeping and linear-time scanning of long strings with an early exit.
Constraints
- 1 <= len(s) <= 10^5 and 1 <= len(p) <= 10^5
- s and p consist only of lowercase English letters 'a' to 'z'.
- len(p) may exceed len(s); the answer is then -1.
- The result is -1 or an index below 10^5, so it never exceeds 2^31 - 1 and fits in a 32-bit int.
Examples
Input: ('a', 'a')
Expected Output: 0
Explanation: Minimum sizes: the single letter matches at index 0.
Input: ('a', 'b')
Expected Output: -1
Explanation: Minimum sizes with no match, distinguishing -1 from 0.
Hints
- A qualifying substring always has length exactly len(p); if p is longer than s, there is nothing to check.
- Compare how many times each letter occurs, not just which letters occur: "abb" is not a rearrangement of "aab".
- Examine starting indices from left to right, include the last possible start len(s) - len(p), and stop at the first one that qualifies.