You are given a list of employees' schedules represented as a list of lists of intervals. Each employee has a list of non-overlapping intervals, and these intervals are sorted in ascending order of start time. Your goal is to find the common free time intervals for all employees. An interval represents a period of time where an employee is busy. You need to return the list of intervals representing the free time that is common to all employees.
For example:
Input: [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Explanation:
The employees' schedules are:
Employee 1: [1,2],[5,6]
Employee 2: [1,3]
Employee 3: [4,10]
The common free time is between 3 and 4.
Another example:
Input: [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]
Clarifications:
This problem asks us to find the intervals of time when no employees are working, given a list of employees and their individual schedules.
Edge Cases:
Example:
Input: [[[1,2],[5,6]],[[1,3]],[[4,10]]]
[[1,2],[5,6],[1,3],[4,10]]
[[1,2],[1,3],[4,10],[5,6]]
[[1,3],[4,10]]
[[3,4]]
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def employee_free_time_naive(schedule):
intervals = []
for employee in schedule:
for interval in employee:
intervals.append(interval)
intervals.sort(key=lambda x: x.start)
merged = []
if intervals:
merged.append(Interval(intervals[0].start, intervals[0].end))
for interval in intervals[1:]:
if interval.start <= merged[-1].end:
merged[-1].end = max(merged[-1].end, interval.end)
else:
merged.append(Interval(interval.start, interval.end))
free_time = []
for i in range(len(merged) - 1):
free_time.append(Interval(merged[i].end, merged[i+1].start))
return free_time
We can use a min-heap to efficiently find the free time. The min-heap will store intervals, prioritized by their start times.
import heapq
class Interval:
def __init__(self, start, end):
self.start = start
self.end = end
def __lt__(self, other):
return self.start < other.start
def employee_free_time(schedule):
min_heap = []
for employee in schedule:
if employee:
heapq.heappush(min_heap, (employee[0].start, employee[0].end, schedule.index(employee), 0))
free_time = []
last_interval = Interval(float('-inf'), float('-inf'))
while min_heap:
start, end, emp_idx, interval_idx = heapq.heappop(min_heap)
curr_interval = Interval(start, end)
if curr_interval.start > last_interval.end:
free_time.append(Interval(last_interval.end, curr_interval.start))
last_interval = Interval(max(last_interval.start, curr_interval.start), max(last_interval.end, curr_interval.end))
if interval_idx + 1 < len(schedule[emp_idx]):
next_interval = schedule[emp_idx][interval_idx + 1]
heapq.heappush(min_heap, (next_interval.start, next_interval.end, emp_idx, interval_idx + 1))
return free_time