Maximum Gap Between Stations Problem
Description
LeetCode Problem 4026.
You are given two strings skill and station of lengths n and m, respectively.
skill[i] represents the skill of worker i, and station[j] represents the skill supported by station j.
You must assign every worker to a distinct station. Let j_i be the index of the station assigned to worker i. A valid assignment must satisfy:
station[j_i] == skill[i]for every0 <= i < n.- The assigned station indices must be strictly increasing in worker order, meaning
j_0 < j_1 < ... < j_(n - 1).
The gap of an assignment is the maximum difference between the station indices assigned to two consecutive workers. In other words, it is max(j_i - j_(i - 1)) over all 1 <= i < n.
If there is only one worker, the gap is 0.
Return the maximum possible gap among all valid assignments. It is guaranteed that at least one valid assignment exists.
Example 1:
Input: skill = "aa", station = "aaaa"
Output: 3
Explanation:
- The two workers must be assigned to two different 'a' stations.
- Assigning them to stations [0, 3] gives a gap of 3.
Example 2:
Input: skill = "xyz", station = "xyzz"
Output: 2
Explanation:
- Assign worker 0 to station j = 0, and worker 1 to station j = 1.
- To maximize the gap, assign worker 2 to station j = 3.
- This gives the assignment [0, 1, 3] with gaps [1, 2], so the gap is 2.
Example 3:
Input: skill = "cbc", station = "cbcdbc"
Output: 4
Explanation:
- Assign worker 0 to station j = 0, and worker 1 to station j = 1.
- To maximize the gap, assign worker 2 to station j = 5.
- This gives the assignment [0, 1, 5] with gaps [1, 4], so the gap is 4.
Constraints:
skill.length == nstation.length == m1 <= n <= m <= 10^5skillandstationconsist of lowercase English letters.- It is guaranteed that a valid assignment exists for every worker.
Solution
Approach: Greedy
The largest gap is between some pair of consecutive workers i and i + 1. To make that pair's gap as large as possible, workers 0..i should sit as far left as possible and workers i + 1..n - 1 as far right as possible.
First scan from the right and store in suf[i] the rightmost station worker i can take while leaving valid stations for all workers after it. Then scan from the left, put worker i on the leftmost matching station pre, and update the answer with suf[i + 1] - pre. With a single worker the answer is 0.
Complexity: time O(n + m), space O(n), where n = skill.length and m = station.length.
class Solution:
def maximumGap(self, skill: str, station: str) -> int:
n, m = len(skill), len(station)
suf = [0] * n
j = m - 1
for i in range(n - 1, 0, -1):
while station[j] != skill[i]:
j -= 1
suf[i] = j
j -= 1
ans = pre = 0
for i in range(n - 1):
while station[pre] != skill[i]:
pre += 1
ans = max(ans, suf[i + 1] - pre)
pre += 1
return ans