Find start indices of a pattern that lie within k positions of another pattern's occurrence
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Other
Overview: Find every start index of pattern a in a string that has an occurrence of pattern b starting within k positions of it, returned in ascending order. It tests substring matching, working with sorted lists of positions, and using binary search or two pointers to keep the distance check fast on long inputs.
Constraints
- 1 <= k <= len(s) <= 10^5
- 1 <= len(a), len(b) <= 10
- s, a and b contain only lowercase English letters.
Examples
Input: ('isawsquirrelnearthesquirrelpark', 'squirrel', 'park', 15)
Expected Output: [19]
Explanation: Source example 1. s has length 31: squirrel starts at 4 and 19, park at 27, and only 19 is within 15.
Input: ('abcd', 'a', 'a', 4)
Expected Output: [0]
Explanation: Source example: a equals b, so the only occurrence at 0 pairs with itself at distance 0, with k = len(s) = 4.
Hints
- Find every start of each pattern, including starts whose occurrences overlap; a pattern longer than s has no start at all.
- For a fixed start i of a, only starts of b in the closed range from i - k to i + k matter, and both ends of that range count.
- When a and b are the same string, an occurrence of a also serves as its own b at distance 0.