Meeting Scheduler Problem
Description
LeetCode Problem 1229.
Given the availability time slots arrays slots1 and slots2 of two people and a meeting duration duration, return the earliest time slot that works for both of them and is of duration duration.
If there is no common time slot that satisfies the requirements, return an empty array.
The format of a time slot is an array of two elements [start, end] representing an inclusive time range from start to end.
It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots [start1, end1] and [start2, end2] of the same person, either start1 > end2 or start2 > end1.
Example 1:
Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8
Output: [60,68]
Example 2:
Input: slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12
Output: []
Constraints:
1 <= slots1.length, slots2.length <= 10^4slots1[i].length, slots2[i].length == 2slots1[i][0] < slots1[i][1]slots2[i][0] < slots2[i][1]0 <= slots1[i][j], slots2[i][j] <= 10^91 <= duration <= 10^6
Solution
Approach: Sort + Two Pointers
The slots are not given in order, so sort both lists by start time. Then walk through them with one pointer each, i in slots1 and j in slots2.
The two current slots overlap from start = max(start1, start2) to end = min(end1, end2). If end - start >= duration, the meeting fits, and [start, start + duration] is the answer: everything skipped so far could not hold the meeting, and this is the earliest start inside this overlap.
Otherwise drop the slot that ends first. The other person's slots do not intersect, so each of their later slots starts after their current slot ends, which is no earlier than the end of the slot that ends first. So the slot that ends first cannot overlap anything still to come, and advancing its pointer never skips an answer. If either list runs out, there is no common time and the answer is an empty array.
Complexity: O(m log m + n log n) time for sorting and O(m + n) for the scan; O(log m + log n) extra space for sorting.
class Solution:
def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
slots1.sort()
slots2.sort()
i = j = 0
while i < len(slots1) and j < len(slots2):
start = max(slots1[i][0], slots2[j][0])
end = min(slots1[i][1], slots2[j][1])
if end - start >= duration:
return [start, start + duration]
# The slot that ends first cannot overlap anything later of the other person.
if slots1[i][1] < slots2[j][1]:
i += 1
else:
j += 1
return []