759. Employee Free Time
Asked at 11Apple30Google25Amazon18Bloomberg8.3Microsoft7.5Meta5.0Capital One35Citadel69Airbnb69Intuit43TikTok26
Problem
schedule[i] lists employee i's working intervals, sorted and non-overlapping. Return the finite intervals of positive length during which all employees are free, sorted.
Example: [[[1,2],[5,6]],[[1,3]],[[4,10]]] → [[3,4]]
Problem (Premium): each employee has a sorted list of non-overlapping working Intervals. Return the finite intervals (positive length) when everyone is free, sorted.
Nobody's identity matters: flatten all intervals, sort by start and sweep while tracking the furthest end so far. Any start beyond that end leaves a common gap (end, start). (A min-heap k-way merge avoids the full sort: O(N log k).)
Complexity: O(N log N) for N intervals.
class Interval: # provided by LeetCode
def __init__(self, start: int = None, end: int = None):
self.start = start
self.end = end
class Solution:
def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]':
ivs = sorted((iv for emp in schedule for iv in emp), key=lambda iv: iv.start)
res, end = [], ivs[0].end
for iv in ivs[1:]:
if iv.start > end:
res.append(Interval(end, iv.start))
end = max(end, iv.end)
return res
def free(s):
return [[iv.start, iv.end] for iv in Solution().employeeFreeTime([[Interval(a, b) for a, b in emp] for emp in s])]
assert free([[[1, 2], [5, 6]], [[1, 3]], [[4, 10]]]) == [[3, 4]]
assert free([[[1, 3], [6, 7]], [[2, 4]], [[2, 5], [9, 12]]]) == [[5, 6], [7, 9]]
assert free([[[1, 2]], [[2, 3]]]) == []
assert free([[[1, 2], [8, 9]], [[3, 4]]]) == [[2, 3], [4, 8]]
class Interval { // provided by LeetCode
public int start, end;
public Interval() {}
public Interval(int _start, int _end) { start = _start; end = _end; }
}
class Solution {
public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
List<Interval> all = new ArrayList<>();
for (List<Interval> emp : schedule) all.addAll(emp);
all.sort((a, b) -> Integer.compare(a.start, b.start));
List<Interval> res = new ArrayList<>();
int end = all.get(0).end;
for (Interval iv : all) {
if (iv.start > end) res.add(new Interval(end, iv.start));
end = Math.max(end, iv.end);
}
return res;
}
}
type Interval struct { // provided by LeetCode
Start int
End int
}
func employeeFreeTime(schedule [][]*Interval) []*Interval {
ivs := []*Interval{}
for _, emp := range schedule { // whose interval it is does not matter
ivs = append(ivs, emp...)
}
sort.Slice(ivs, func(i, j int) bool { return ivs[i].Start < ivs[j].Start })
res := []*Interval{}
end := ivs[0].End // furthest busy time so far
for _, iv := range ivs[1:] {
if iv.Start > end {
res = append(res, &Interval{Start: end, End: iv.Start})
}
end = max(end, iv.End)
}
return res
}