Approach #1: Events (Line Sweep) [Accepted]


If some interval overlaps any interval (for any employee), then it won't be included in the answer. So we could reduce our problem to the following: given a set of intervals, find all places where there are no intervals.

To do this, we can use an "events" approach present in other interval problems. For each interval [s, e], we can think of this as two events: balance++ when time = s, and balance-- when time = e. We want to know the regions where balance == 0.


For each interval, create two events as described above, and sort the events. Now for each event occuring at time t, if the balance is 0, then the preceding segment [prev, t] did not have any intervals present, where prev is the previous value of t.

Complexity Analysis

  • Time Complexity: , where is the number of intervals across all employees.

  • Space Complexity: .

Approach #2: Priority Queue [Accepted]


Say we are at some time where no employee is working. That work-free period will last until the next time some employee has to work.

So let's maintain a heap of the next time an employee has to work, and it's associated job. When we process the next time from the heap, we can add the next job for that employee.


Keep track of the latest time anchor that we don't know of a job overlapping that time.

When we process the earliest occurring job not yet processed, it occurs at time t, by employee e_id, and it was that employee's e_jx'th job. If anchor < t, then there was a free interval Interval(anchor, t).

Complexity Analysis

  • Time Complexity: , where is the number of employees, and is the number of jobs across all employees. The maximum size of the heap is , so each push and pop operation is , and there are such operations.

  • Space Complexity: in additional space complexity.

Analysis written by: @awice.