Solution: Employee Free Time
Let's solve the Employee Free Time problem using the Merge Intervals pattern.
We'll cover the following
Statement#
You’re given a list containing the schedules of multiple employees. Each person’s schedule is a list of non-overlapping intervals in a sorted order. An interval is specified with the start and end time, both being positive integers. Your task is to find the list of finite intervals representing the free time for all the employees.
Constraints:
-
schedule.length,schedule[i].length -
interval.start<interval.end, whereintervalis any interval in the list of schedules.
Solution#
The intuition behind this solution involves merging the individual schedules of all employees into a unified timeline. By doing this, we can identify the common free time intervals where none of the employees are occupied. The key idea is to find the gaps or intervals between the time slots of these merged schedules.
We use the following variables in our solution:
previous: Stores the end time of the previously processed interval.i: Stores the employee’s index value.j: Stores the interval’s index of the employee,i.result: Stores the free time intervals.
The steps of the algorithm are given below:
- We store the start time of each employee’s first interval along with its index value and a value
0into a min-heap. - We set
previousto the start time of the first interval present in a heap. - Then we iterate a loop until the heap is empty, and in each iteration, we do the following:
- Pop an element from the min-heap and set
iandjto the second and third values, respectively, from the popped value. - Select the interval from input located at
i,j. - If the selected interval’s start time is greater than
previous, it means that the time frompreviousto the selected interval’s start time is free. So, add this interval to theresultarray. - Now, update the
previousas . - If the current employee has any other interval, push it into the heap.
- Pop an element from the min-heap and set
- After all the iterations, when the heap becomes empty, return the
resultarray.
1 of 7
2 of 7
3 of 7
4 of 7
5 of 7
6 of 7
7 of 7
Let’s look at the code for this solution below:
Time complexity#
The time complexity of the solution is , where is the number of employees and is the number of intervals. This is because the heap can contain a maximum of elements.
Space complexity#
We use a heap in the solution, which can have a maximum of elements. Hence, the space complexity of this solution is , where is the number of employees.
Employee Free Time
K-way Merge: Introduction