Employee Free Time

Find the hours when every employee is free at once, given each employee's working hours.

Each employee's working hours are given as a list of intervals [start, end], sorted by start, with no two intervals of the same employee overlapping. Return, sorted by start, every interval of time in which all employees are free. Leave out the free time before the first working hour and after the last one, because it has no start or no end.

Example 1
Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
Output: [[3,4]]
Example 2
Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
Output: [[5,6],[7,9]]
Solution

The Idea

Think of three colleagues trying to book a meeting room for a talk all of them must attend. Each one has a calendar full of work blocks, and the talk can only go where none of the three calendars is blocked.

Example 2 is such a set of calendars. The first employee works [[1,3],[6,7]], which means from 1 to 3 and again from 6 to 7. The second works from 2 to 4, and the third from 2 to 5 and from 9 to 12. Look at the picture below, where each blue bar is one of these intervals.

Example 2 on a timeline from 0 to 13. Employee 1 works 1-3 and 6-7, employee 2 works 2-4, employee 3 works 2-5 and 9-12. The row labelled someone is busy shows 1-5, 6-7 and 9-12, and the shaded gaps 5-6 and 7-9 are free for everyone.

Between 1 and 5, at least one bar always covers the time. At 5 the third employee stops, and nobody starts again until the first employee at 6. So 5-6 is free for everyone. The same happens between 7 and 9. Before 1 and after 12 everyone is free too, but the stretch before 1 has no start and the one after 12 has no end, so the answer leaves them out.

Did it matter whose bar was whose? A moment is useless for the talk as soon as anybody works then, and it does not matter who. So the three rows can be squashed into one, the row labelled "someone is busy". There, 1-3, 2-4 and 2-5 melt into one block 1-5, and the free time is simply the holes between the blocks.

That is the key insight: pour every employee's intervals into one pile, merge the ones that overlap, and the gaps between the merged blocks are the answer. Merging overlapping intervals after sorting them by start is the same work as in Merge Intervals, except that here the gaps are what we report.

Solution Approach

Turning that idea into code means settling three things: how to put the intervals in time order, how to tell when a gap opens up, and which gaps to report. A faster way to get the time order, for long schedules, comes at the end as an option.

Putting the intervals in time order

How do we walk through time when the intervals sit in separate lists? Each list is sorted, but the lists interleave. Copying all of them into one list and sorting it by start time gives a single order: for Example 2, 1-3, 2-4, 2-5, 6-7, 9-12.

Telling when a gap opens

What do we need to remember while walking this list? Only the moment until which someone is busy, which is the latest end seen so far. The code keeps it in a variable named busyUntil. When the next interval starts after busyUntil, nobody works between the two moments, so that stretch is free for everyone.

Why the latest end, and not the end of the interval just before? Because a long interval can cover several short ones after it. Take one employee working 1-10 and another working 2-3 and 5-6. After 2-3, the end of the previous interval is 3, and 5-6 starts later, but the first employee is still busy until 10. Keeping the largest end with Math.max carries the 10 along.

Which gaps to report

What about the free time before the first interval? A gap always begins at busyUntil, and busyUntil starts at the end of the first interval, so no gap can begin before that interval. After the last interval no later start comes along, so the open stretch at the end is skipped too.

And when one interval ends exactly where the next starts, such as 1-3 and 3-4? The check is "starts after", a strict >, so the empty moment at 3 is not reported as a gap.

Optional: merging the sorted lists instead of sorting everything

Is a full sort wasteful when each employee's list is already sorted? With many intervals per employee, a little. A PriorityQueue set up as a min-heap ordered by start, so that it always hands out the interval with the smallest start first, can hold the next unread interval of each employee. Taking intervals out of it one by one, and putting in that employee's next interval each time, gives the same time order. Each step then costs log k for k employees, instead of log N for N intervals. The walk with busyUntil stays the same.

Java Solution

The method employeeFreeTime works in these steps:

  1. First, copy every employee's intervals into one list, all, with a loop over the employees. Each interval is an int[] of two numbers, start and end.
  2. Sort all by start time with all.sort(...) and a comparator that compares the first numbers.
  3. Create an empty list free for the answer, and set busyUntil to the end of the first interval in all.
  4. Walk through all with a second loop. For each interval, named shift, check whether it starts after busyUntil. If it does, add the gap from busyUntil to that start to free.
  5. Still inside that loop, raise busyUntil to the end of shift if that end is later.
  6. After the last interval, free holds the gaps in time order, and the method returns that list.

Two short helpers, schedule and show, build the input and print the result in the bracket form of the examples. The main method runs both examples, the 1-10 case from above, two employees whose intervals touch at 3, and a single employee.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class EmployeeFreeTime {

    public static List<int[]> employeeFreeTime(List<List<int[]>> schedule) {
        List<int[]> all = new ArrayList<>();
        for (List<int[]> employee : schedule) {
            all.addAll(employee);                 // whose shift it is does not matter
        }
        all.sort((a, b) -> Integer.compare(a[0], b[0]));

        List<int[]> free = new ArrayList<>();
        int busyUntil = all.get(0)[1];
        for (int[] shift : all) {
            if (shift[0] > busyUntil) {
                free.add(new int[] {busyUntil, shift[0]});  // nobody is busy in between
            }
            busyUntil = Math.max(busyUntil, shift[1]);
        }
        return free;
    }

    // Builds the schedule from the bracket form of the examples, one array per employee.
    static List<List<int[]>> schedule(int[][]... employees) {
        List<List<int[]>> result = new ArrayList<>();
        for (int[][] shifts : employees) {
            result.add(Arrays.asList(shifts));
        }
        return result;
    }

    static String show(List<int[]> intervals) {
        List<String> parts = new ArrayList<>();
        for (int[] iv : intervals) {
            parts.add(Arrays.toString(iv));
        }
        return parts.toString();
    }

    public static void main(String[] args) {
        System.out.println(show(employeeFreeTime(schedule(
            new int[][] {{1, 2}, {5, 6}}, new int[][] {{1, 3}}, new int[][] {{4, 10}}))));
        System.out.println(show(employeeFreeTime(schedule(
            new int[][] {{1, 3}, {6, 7}}, new int[][] {{2, 4}}, new int[][] {{2, 5}, {9, 12}}))));
        System.out.println(show(employeeFreeTime(schedule(
            new int[][] {{1, 10}}, new int[][] {{2, 3}, {5, 6}}))));
        System.out.println(show(employeeFreeTime(schedule(
            new int[][] {{1, 3}}, new int[][] {{3, 4}}))));
        System.out.println(show(employeeFreeTime(schedule(
            new int[][] {{1, 2}, {4, 6}, {8, 9}}))));
    }
}

Running it prints:

Output
[[3, 4]]
[[5, 6], [7, 9]]
[]
[]
[[2, 4], [6, 8]]

Example 1 gives [[3, 4]]: the employees cover 1 to 3 together, and the third one only starts at 4. Example 2 gives [[5, 6], [7, 9]], the two shaded gaps from the picture.

Look at the third line, the 1-10 case. It is empty because busyUntil stays at 10 while 2-3 and 5-6 go by. If the code sets busyUntil = shift[1] instead of taking Math.max, that line prints [[3, 5]], a gap in which the first employee is still at work.

The fourth line is empty too: 1-3 and 3-4 touch, and the strict > reports no gap at 3. The last line shows that with one employee, the free time is just the space between that employee's own intervals, 2-4 and 6-8.

Complexity

The sort is the most expensive part; copying the intervals and the walk with busyUntil each touch every interval once.

  • Time: O(N log N), because the N intervals of all employees together are sorted by start, while the copy and the walk with busyUntil do a fixed amount of work per interval.
  • Space: O(N), because the pooled list all holds a reference to every interval, and the answer free can hold at most N - 1 gaps, one between each two intervals that follow each other in time order.