Maximum Team Size with Overlapping Intervals Problem
Description
LeetCode Problem 3893.
You are given two integer arrays startTime and endTime of length n.
startTime[i]represents the start time of thei^themployee.endTime[i]represents the end time of thei^themployee.
Two employees i and j can interact if their time intervals overlap. Two intervals are considered overlapping if they share at least one common time point.
A team is valid if there exists at least one employee in the team who can interact with every other member of the team.
Return an integer denoting the maximum possible size of such a team.
Example 1:
Input: startTime = [1,2,3], endTime = [4,5,6]
Output: 3
Explanation:
- For i = 0 with interval [1, 4].
- It overlaps with i = 1 having interval [2, 5] and i = 2 having interval [3, 6].
- Thus, index 0 can interact with all other indices, so the team size is 3.
Example 2:
Input: startTime = [2,5,8], endTime = [3,7,9]
Output: 1
Explanation:
- For i = 0, interval [2, 3] does not overlap with [5, 7] or [8, 9].
- For i = 1, interval [5, 7] does not overlap with [2, 3] or [8, 9].
- For i = 2, interval [8, 9] does not overlap with [2, 3] or [5, 7].
- Thus, no index can interact with others, so the maximum team size is 1.
Example 3:
Input: startTime = [3,4,6], endTime = [8,5,7]
Output: 3
Explanation:
- For i = 0 with interval [3, 8].
- It overlaps with i = 1 having interval [4, 5] and i = 2 having interval [6, 7].
- Thus, index 0 can interact with all other indices, so the team size is 3.
Constraints:
1 <= n == startTime.length == endTime.length <= 10^50 <= startTime[i] <= endTime[i] <= 10^9
Solution
Approach: Binary Search
A team is built around one employee i who overlaps with everyone else, so the best team for i is i together with every employee whose interval overlaps [l, r]. We only need to count those employees for each i and take the maximum.
Sort all start times and all end times separately. Two intervals overlap exactly when one starts no later than the other ends, and the other way around. For employee i with interval [l, r]:
j= number of employees with start time<= r(binary search in the sorted starts).i'= number of employees with end time< l(binary search in the sorted ends). Each of them also starts beforer, so they are all counted inj.
So j - i' employees overlap with [l, r] (including employee i itself). The answer is the maximum of this value over all employees.
Complexity:
- Time complexity:
O(n log n). - Space complexity:
O(n).
from bisect import bisect_right
class Solution:
def maximumTeamSize(self, startTime: List[int], endTime: List[int]) -> int:
intervals = list(zip(startTime, endTime))
startTime.sort()
endTime.sort()
ans = 0
for l, r in intervals:
i = bisect_right(endTime, l - 1)
j = bisect_right(startTime, r)
ans = max(ans, j - i)
return ans