Coding Interview PatternsEmployee Free Time
HardIntervals

Employee Free Time

Explanation & Solution

Description

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 the common, positive-length free time for all employees, also in sorted order.

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 [3,4].

Constraints

  • 1 <= schedule.length <= 50
  • 1 <= schedule[i].length <= 50
  • 0 <= schedule[i][j][0] < schedule[i][j][1] <= 10^8
  • Each employee's intervals are non-overlapping and sorted by start time

Approach

Intervals pattern

1. Flatten All Intervals

  • Iterate through every employee's schedule and collect all intervals into a single flat list
  • We don't care which employee an interval belongs to — we only care about overall coverage

2. Sort by Start Time

  • Sort all the flattened intervals by their start value in ascending order
  • This sets up the merge step by ensuring overlapping intervals are adjacent

3. Merge Overlapping Intervals

  • Initialize a merged array with the first sorted interval
  • For each subsequent interval, compare its start with the last merged interval's end
  • If overlapping (curr[0] <= last[1]): extend the end to Math.max(last[1], curr[1])
  • If not overlapping (curr[0] > last[1]): push it as a new merged interval

4. Find Gaps Between Merged Intervals

  • After merging, any gap between consecutive merged intervals is a period when no employee is working
  • For each pair of consecutive merged intervals, the gap is [merged[i-1][1], merged[i][0]]
  • These gaps are the common free time

5. Return Result

  • The gaps are already in sorted order because the merged intervals are sorted
  • Return the list of free time intervals

Key Insight

This problem reduces to two well-known sub-problems: merge intervals followed by gap finding. Once you flatten all employee schedules into one list and merge overlapping intervals, the free time is simply the space between consecutive merged intervals. The per-employee structure is a red herring — it doesn't affect the algorithm at all.

Visualization

Input:
Interval Timeline[[1,2], [5,6], [1,3], [4,10]]
Input[1,2][5,6][1,3][4,10]12345678910

Press play to start visualization

CurrentCompareOverlapMerged
9 steps

Solution Code