15% off all plans & roadmaps Use code
See plansEmployee Free Time
- LeetCode 759
- Hard
- Greedy Patterns
- Line Sweep
Updated
TL;DR: You get the working intervals of several employees and must report every gap where nobody works. Sort all intervals by start, then sweep once while tracking the furthest end seen so far.
Problem
You are given a list schedule, where schedule[i] holds the working intervals of the i-th employee. Each employee's intervals are sorted and do not overlap. Every interval is a list [start, end] that is closed on the left and open on the right, so it covers the times from start up to but not including end.
Find every finite interval during which all employees are free, meaning no employee is working. Do not return free time before the earliest start or after the latest end across all schedules. Return the intervals sorted in ascending order by start, where each interval is a list [start, end].
Example 1
Input: schedule = [[[1, 2], [2, 3]], [[3, 4]]] Output: []
Constraints
1 <= schedule.length <= 501 <= schedule[i].length <= 500 <= start < end <= 10^8
Constraints that matter
- The total number of intervals N is at most 2,500 (50 employees with 50 intervals each). An O(N^2) pair check fits in that budget.
- Times reach 10^8, so scanning every time unit is too slow. The work must depend on the number of intervals, not on the size of the time range.
- Each employee's list is sorted, but the lists interleave across employees. You need one global sort or a k-way merge to see the full coverage.
- Intervals are half-open. [1, 2) and [2, 3) leave no gap, so the gap test must be a strict comparison.
Hints
Hint 1
Free time is the complement of working time.
Hint 2
A free block can only begin at an end time.
Solution
Intuition
Free time is the complement of working time. Merge every interval from every employee into one picture of the timeline. The covered blocks leave holes between them, and each hole is a free block. This is a line sweep problem: you move a point from left to right and watch the coverage change.
Picture a single bookmark sliding along a row of tape strips laid end to end. The bookmark marks the furthest point covered so far, and any bare stretch of floor it passes over is free time.
The phrase all employees points you to a global view. Each employee's list is sorted, but the lists interleave, so you cannot walk them one at a time. Sort the whole set by start time and sweep once. The only state you carry is one number, the furthest end seen so far.
Many guides use an event counter instead, with +1 at each start and -1 at each end. Process starts before ends at equal times, and it gives the same answer.
This works because of the sort. Every interval you have processed starts no later than the current one. Those processed intervals end at or before the furthest value, so no time up to furthest can be free. Unprocessed intervals start at or after the current start. A stretch from furthest up to the current start is therefore inside no interval at all.
Worked example
Input: schedule = [[[1, 2], [2, 3]], [[3, 4]]] Output: [] Explanation: Employee 1 works [1, 2) and [2, 3). Employee 2 works [3, 4). Together they cover [1, 4) with no break. The touching intervals at 2 and 3 leave no gap, so the answer is empty.
Approach 1: Brute force: check every end time against every interval
A free block can only begin at an end time. Right before the start of a free block, some interval must have ended. So you can treat each distinct end time as a candidate start.
For each candidate, check every interval to see whether one still covers that time. If none does, scan every interval for the nearest start after the candidate. That start closes the free block.
This is the naive version because it compares every candidate against every interval, twice. It never looks at the time range directly, so it stays correct for huge values.
Steps
- Flatten the nested schedule into one list of intervals.
- Collect the distinct end times and sort them ascending. These are the candidate starts.
- For each candidate t, check every interval. If some interval has start <= t < end, skip t.
- Otherwise, find the smallest start that is greater than t across all intervals. If none exists, skip t, because it lies after all work.
- Append [t, nearest start] to the result. Candidates are processed in order, so the result is already sorted.
Dry run
The flattened intervals are [1, 2], [2, 3], [3, 4]. The distinct end times are 2, 3 and 4.
- Candidate 2: [1, 2] does not cover 2 because 2 is not less than 2. [2, 3] covers 2. Skip.
- Candidate 3: [2, 3] does not cover 3. [3, 4] covers 3. Skip.
- Candidate 4: no interval covers 4. No start is greater than 4, so there is no closing start. Skip.
No block is added, and the result is [], which matches the example.
Complexity
| Time | O(N^2) |
|---|---|
| Space | O(N) |
Let N be the total number of intervals. There are at most N distinct end times. Each one triggers a full scan of N intervals for the covered check and another full scan for the nearest start.
That is about 2 * N * N steps, so the time is O(N^2). Sorting the candidates costs O(N log N), which the quadratic work dominates. The flattened list, the candidate list and the result each hold at most N items, so the space is O(N).
PythonTested in our runner
from typing import List, Optional
class Solution:
def employeeFreeTime(self, schedule: List[List[List[int]]]) -> List[List[int]]:
intervals = [iv for emp in schedule for iv in emp]
ends = sorted(set(end for _, end in intervals))
result = []
for t in ends:
# Skip t if some interval is still working at time t
if any(start <= t < end for start, end in intervals):
continue
# Otherwise the free block runs until the nearest later start
later = [start for start, _ in intervals if start > t]
if later:
result.append([t, min(later)])
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[][] employeeFreeTime(int[][][] schedule) {
List<int[]> intervals = new ArrayList<>();
for (int[][] emp : schedule) {
for (int[] iv : emp) {
intervals.add(iv);
}
}
TreeSet<Integer> ends = new TreeSet<>();
for (int[] iv : intervals) {
ends.add(iv[1]);
}
List<int[]> result = new ArrayList<>();
for (int t : ends) {
boolean covered = false;
for (int[] iv : intervals) {
if (iv[0] <= t && t < iv[1]) {
covered = true;
break;
}
}
if (covered) {
continue;
}
boolean found = false;
int next = 0;
for (int[] iv : intervals) {
if (iv[0] > t && (!found || iv[0] < next)) {
next = iv[0];
found = true;
}
}
if (found) {
result.add(new int[]{t, next});
}
}
return result.toArray(new int[0][]);
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<vector<int>> employeeFreeTime(vector<vector<vector<int>>>& schedule) {
vector<vector<int>> intervals;
for (auto& emp : schedule) {
for (auto& iv : emp) {
intervals.push_back(iv);
}
}
set<int> ends;
for (auto& iv : intervals) {
ends.insert(iv[1]);
}
vector<vector<int>> result;
for (int t : ends) {
bool covered = false;
for (auto& iv : intervals) {
if (iv[0] <= t && t < iv[1]) {
covered = true;
break;
}
}
if (covered) continue;
bool found = false;
int next = 0;
for (auto& iv : intervals) {
if (iv[0] > t && (!found || iv[0] < next)) {
next = iv[0];
found = true;
}
}
if (found) result.push_back({t, next});
}
return result;
}
};JavaScriptTested in our runner
var employeeFreeTime = function(schedule) {
const intervals = [];
for (const emp of schedule) {
for (const iv of emp) intervals.push(iv);
}
const ends = [...new Set(intervals.map(iv => iv[1]))].sort((a, b) => a - b);
const result = [];
for (const t of ends) {
// Skip t if some interval is still working at time t
if (intervals.some(([s, e]) => s <= t && t < e)) continue;
// Otherwise the free block runs until the nearest later start
const later = intervals.filter(([s]) => s > t).map(([s]) => s);
if (later.length > 0) result.push([t, Math.min(...later)]);
}
return result;
};GoTested in our runner
package main
import "sort"
func employeeFreeTime(schedule [][][]int) [][]int {
var intervals [][]int
for _, emp := range schedule {
for _, iv := range emp {
intervals = append(intervals, iv)
}
}
seen := map[int]bool{}
var ends []int
for _, iv := range intervals {
if !seen[iv[1]] {
seen[iv[1]] = true
ends = append(ends, iv[1])
}
}
sort.Ints(ends)
result := [][]int{}
for _, t := range ends {
covered := false
for _, iv := range intervals {
if iv[0] <= t && t < iv[1] {
covered = true
break
}
}
if covered {
continue
}
found := false
next := 0
for _, iv := range intervals {
if iv[0] > t && (!found || iv[0] < next) {
next = iv[0]
found = true
}
}
if found {
result = append(result, []int{t, next})
}
}
return result
}C#Tested in our runner
public class Solution {
public int[][] employeeFreeTime(int[][][] schedule) {
var intervals = new List<int[]>();
foreach (var emp in schedule) {
foreach (var iv in emp) intervals.Add(iv);
}
var ends = new SortedSet<int>();
foreach (var iv in intervals) ends.Add(iv[1]);
var result = new List<int[]>();
foreach (int t in ends) {
bool covered = false;
foreach (var iv in intervals) {
if (iv[0] <= t && t < iv[1]) { covered = true; break; }
}
if (covered) continue;
bool found = false;
int next = 0;
foreach (var iv in intervals) {
if (iv[0] > t && (!found || iv[0] < next)) {
next = iv[0];
found = true;
}
}
if (found) result.Add(new int[] { t, next });
}
return result.ToArray();
}
}The Line Sweep infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
Line Sweep
Part of Greedy Patterns
Approach 2: Sort by start, then sweep with the furthest endOptimalLine Sweep
What's slow: the brute force re-reads all N intervals for every candidate, twice. Most of those reads answer the same question, which is whether the timeline is still covered at this point.
The insight that fixes it: once the intervals are sorted by start, you do not need to look back at earlier intervals. Only the furthest end among the processed intervals matters. If the next start is past that end, the gap is free. If not, the next interval extends coverage, so you update the furthest end and move on.
Steps
- Flatten the nested schedule into one list of intervals.
- If the list is empty, return an empty result.
- Sort the list by start, breaking ties by end.
- Set furthest to the end of the first interval.
- For each following interval [s, e], if s is greater than furthest, append [furthest, s] to the result.
- Set furthest to the larger of furthest and e.
- Return the result. The sweep moves left to right, so the blocks are already sorted.
Dry run
The intervals are already sorted: [1, 2], [2, 3], [3, 4]. The sweep starts with furthest = 2 from the first interval. The table below shows each step.
| Step | Interval [s, e] | Check: s > furthest? | Block added | furthest after step |
|---|---|---|---|---|
| 0 | [1, 2] (sets furthest) | not checked | none | 2 |
| 1 | [2, 3] | 2 > 2? no | none | max(2, 3) = 3 |
| 2 | [3, 4] | 3 > 3? no | none | max(3, 4) = 4 |
The touching intervals at 2 and 3 fail the strict check, so no zero-length block appears. The result is [], which matches the example.
Complexity
| Time | O(N log N) |
|---|---|
| Space | O(N) |
Let N be the total number of intervals. Flattening visits each interval once, which costs O(N). Sorting the N intervals takes O(N log N) comparisons, and that term dominates.
The sweep visits each interval once and does O(1) work per visit, so it costs O(N). The flattened list and the output each hold at most N items, so the space is O(N), plus the extra memory the sort uses internally.
PythonTested in our runner
from typing import List, Optional
class Solution:
def employeeFreeTime(self, schedule: List[List[List[int]]]) -> List[List[int]]:
intervals = [iv for emp in schedule for iv in emp]
if not intervals:
return []
# Sort by start, then by end
intervals.sort()
result = []
furthest = intervals[0][1]
for start, end in intervals[1:]:
# A gap exists only when the next start is strictly past furthest
if start > furthest:
result.append([furthest, start])
furthest = max(furthest, end)
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int[][] employeeFreeTime(int[][][] schedule) {
List<int[]> intervals = new ArrayList<>();
for (int[][] emp : schedule) {
for (int[] iv : emp) {
intervals.add(iv);
}
}
if (intervals.isEmpty()) {
return new int[0][];
}
intervals.sort((a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0]) : Integer.compare(a[1], b[1]));
List<int[]> result = new ArrayList<>();
int furthest = intervals.get(0)[1];
for (int i = 1; i < intervals.size(); i++) {
int[] iv = intervals.get(i);
// A gap exists only when the next start is strictly past furthest
if (iv[0] > furthest) {
result.add(new int[]{furthest, iv[0]});
}
furthest = Math.max(furthest, iv[1]);
}
return result.toArray(new int[0][]);
}
}C++Tested in our runner
using namespace std;
class Solution {
public:
vector<vector<int>> employeeFreeTime(vector<vector<vector<int>>>& schedule) {
vector<vector<int>> intervals;
for (auto& emp : schedule) {
for (auto& iv : emp) {
intervals.push_back(iv);
}
}
vector<vector<int>> result;
if (intervals.empty()) return result;
// Sort by start, then by end
sort(intervals.begin(), intervals.end());
int furthest = intervals[0][1];
for (size_t i = 1; i < intervals.size(); i++) {
// A gap exists only when the next start is strictly past furthest
if (intervals[i][0] > furthest) {
result.push_back({furthest, intervals[i][0]});
}
furthest = max(furthest, intervals[i][1]);
}
return result;
}
};JavaScriptTested in our runner
var employeeFreeTime = function(schedule) {
const intervals = [];
for (const emp of schedule) {
for (const iv of emp) intervals.push(iv);
}
if (intervals.length === 0) return [];
intervals.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const result = [];
let furthest = intervals[0][1];
for (let i = 1; i < intervals.length; i++) {
const [s, e] = intervals[i];
// A gap exists only when the next start is strictly past furthest
if (s > furthest) result.push([furthest, s]);
furthest = Math.max(furthest, e);
}
return result;
};GoTested in our runner
package main
import "sort"
func employeeFreeTime(schedule [][][]int) [][]int {
var intervals [][]int
for _, emp := range schedule {
for _, iv := range emp {
intervals = append(intervals, iv)
}
}
result := [][]int{}
if len(intervals) == 0 {
return result
}
sort.Slice(intervals, func(i, j int) bool {
if intervals[i][0] != intervals[j][0] {
return intervals[i][0] < intervals[j][0]
}
return intervals[i][1] < intervals[j][1]
})
furthest := intervals[0][1]
for _, iv := range intervals[1:] {
// A gap exists only when the next start is strictly past furthest
if iv[0] > furthest {
result = append(result, []int{furthest, iv[0]})
}
if iv[1] > furthest {
furthest = iv[1]
}
}
return result
}C#Tested in our runner
public class Solution {
public int[][] employeeFreeTime(int[][][] schedule) {
var intervals = new List<int[]>();
foreach (var emp in schedule) {
foreach (var iv in emp) intervals.Add(iv);
}
var result = new List<int[]>();
if (intervals.Count == 0) return result.ToArray();
intervals.Sort((a, b) => a[0] != b[0] ? a[0].CompareTo(b[0]) : a[1].CompareTo(b[1]));
int furthest = intervals[0][1];
for (int i = 1; i < intervals.Count; i++) {
var iv = intervals[i];
// A gap exists only when the next start is strictly past furthest
if (iv[0] > furthest) result.Add(new int[] { furthest, iv[0] });
furthest = Math.Max(furthest, iv[1]);
}
return result.ToArray();
}
}Common mistakes
if start >= furthestin the gap check. Touching intervals like [1, 2] and [2, 3] then produce a zero-length block [2, 2]. Usestart > furthest, because the right end is open.furthest = endinstead offurthest = max(furthest, end). A short interval nested inside a long one lowers furthest. With [1, 10], [2, 3] and [11, 12], this reports [3, 11] instead of [10, 11].furtheststarts at 0 or -1. That reports a free block before the first interval, such as [0, 1] when work starts at 1. Start furthest at the end of the first sorted interval.- Sorting by end time, or not sorting at all. The sweep then meets a later interval before an earlier one, and gaps appear inside covered time. Sort by start.
- Handling each employee's list alone. That finds gaps inside one person's schedule but misses times when someone else works. Flatten all employees into one list before the sweep.
- Looping over every integer from the earliest start to the latest end. Times reach 10^8, so this is too slow. Use the end times as candidates, as the brute force does.
Edge cases
[[[1, 5]]](one employee, one interval): the answer is[]. The sweep never finds a gap, and no free time falls outside the work.[[[1, 2]], [[2, 4]]](touching intervals): the answer is[]. The start 2 is not strictly past furthest 2, so no zero-length block is added.[[[1, 2]], [[4, 5]]](a real gap): the answer is[[2, 4]]. The start 4 is past furthest 2, so the block [2, 4] is recorded.[[[1, 10]], [[2, 3], [4, 5]], [[11, 12]]](nested intervals): the answer is[[10, 11]]. The short intervals must not lower furthest below 10.[[[0, 100000000]], [[50, 60]]](large values): the answer is[]. The sweep does one pass regardless of the size of the time values.
Follow-ups interviewers ask
- What if each employee's list is already sorted and there are only K employees?
- Then you can skip the global sort. Put the first interval of each employee into a min-heap keyed by start, pop the smallest, sweep as before, and push that employee's next interval. This runs in O(N log K), which is better than O(N log N) when K is small. With K at most 50 here, the gain is modest, but the idea scales to many lists.
- What if the intervals do not fit in memory?
- Sort the intervals by start with an external merge sort. Write sorted runs to disk, then merge them as a stream. The sweep only needs the current interval and furthest, so it runs over the sorted stream in one pass and writes each gap to the output as it appears.
Employee Free Time FAQ
What is the time complexity of Employee Free Time?
The sort and sweep solution runs in O(N log N), where N is the total number of intervals across all employees. The sort dominates, and the sweep is linear. The brute force that checks each end time against every interval runs in O(N^2).
Why use a line sweep for Employee Free Time?
A line sweep turns many overlapping intervals into one left-to-right pass. After sorting by start, the only state you need is the furthest end seen so far. That single number tells you exactly when the timeline becomes uncovered.
Can Employee Free Time be solved in O(1) extra space?
Not with a separate copy of the intervals. The sweep state is O(1), but the flattened list costs O(N). Strict O(1) extra space needs an in-place sort of the input, which changes the caller's data.
Why does Employee Free Time need a strict greater than check?
Intervals are open on the right, so an interval ending at time 2 does not cover time 2. A start at time 2 therefore continues the coverage with no gap. Using greater than or equal would add zero-length blocks like [2, 2].
How is Employee Free Time different from Merge Intervals?
Merge Intervals combines overlapping intervals in one list and returns the merged blocks. Employee Free Time starts from several sorted lists, then reports the complement of the union. After you flatten and merge, the holes between the merged blocks are the answer.
Asked at
See which companies ask this — Pro
Related problems
- Partition Labels · same technique: Line Sweep
- Car Pooling · same technique: Line Sweep
- Interval List Intersections · same technique: Line Sweep
- Candy · same pattern: Greedy Patterns
- Merge Intervals · same pattern: Greedy Patterns
- Jump Game · same pattern: Greedy Patterns
- Gas Station · same pattern: Greedy Patterns
- Task Scheduler · same pattern: Greedy Patterns
- Non-overlapping Intervals · same pattern: Greedy Patterns
- Insert Interval · same pattern: Greedy Patterns