Employee Free Time Problem
Description
LeetCode Problem 759.
We are given a list schedule of employees, which represents the working time for each employee.
Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
(Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
Example 1:
Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Explanation: There are a total of three employees, and all common
free time intervals would be [-inf, 1], [3, 4], [10, inf].
We discard any intervals that contain inf as they aren't finite.
Example 2:
Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]
Constraints:
1 <= schedule.length , schedule[i].length <= 500 <= schedule[i].start < schedule[i].end <= 10^8
Solution
Approach: Sort All Intervals and Sweep
Common free time is the time when nobody is working. So we do not need to keep the employees apart: throw all intervals of all employees into one list. The free time is then just the gaps in the union of these intervals.
Sort the combined list by start time and sweep through it while keeping busyUntil, the latest end time seen so far (someone is working until then):
- if the next interval starts after
busyUntil, nobody works betweenbusyUntiland its start, so[busyUntil, start]is a free interval; - in both cases, update
busyUntil = max(busyUntil, end).
Two details matter. First, take the maximum when updating busyUntil: a long interval can contain several later ones ([1,10] covers [2,3] and [4,5]), and using the last interval's end would report fake gaps. Second, use a strict start > busyUntil: when one interval ends exactly where another starts ([1,2] and [2,3]), the gap has zero length and must not be reported. Time before the first interval and after the last one is infinite, so it is never part of the answer.
Complexity: O(N log N) time for sorting, where N is the total number of intervals, and O(N) extra space for the combined list.
"""
# Definition for an Interval.
class Interval:
def __init__(self, start: int = None, end: int = None):
self.start = start
self.end = end
"""
class Solution:
def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]':
# Everyone's intervals in one list, sorted by start time.
intervals = sorted((iv for employee in schedule for iv in employee), key=lambda iv: iv.start)
ans = []
busy_until = intervals[0].end # someone is working until this time
for iv in intervals[1:]:
if iv.start > busy_until: # nobody works in [busy_until, iv.start]
ans.append(Interval(busy_until, iv.start))
busy_until = max(busy_until, iv.end)
return ans