Employee Free Time

Find common free intervals across employee schedules — merge all intervals, take the gaps.

Hard
Time O(n log n) Space O(n)
LeetCode
4 min read
intervals sorting

Problem#

Each employee has a schedule (a list of non-overlapping busy intervals, sorted). Return the list of common free intervals — times when every employee is available — exclusive of leading and trailing infinities.

Examples#

  • [[[1,2],[5,6]],[[1,3]],[[4,10]]][[3,4]]

Constraints#

  • Total intervals up to 5 * 10^4.

Hints#

Hint 1
Flatten all intervals, merge them as in classic merge-intervals; the gaps between consecutive merged blocks are the common free time.

Approach#

Collect every interval into one array, sort by start, merge to produce a maximal “busy” timeline. The complementary gaps are the answer.

Solution#

Employee Free Time
class Solution {
public:
vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {
vector<Interval> all;
for (auto& s : schedule) for (auto& it : s) all.push_back(it);
sort(all.begin(), all.end(), [](const Interval& a, const Interval& b){
return a.start < b.start;
});
vector<Interval> ans;
int end = all[0].end;
for (size_t i = 1; i < all.size(); ++i) {
if (all[i].start > end) {
ans.push_back(Interval(end, all[i].start));
end = all[i].end;
} else {
end = max(end, all[i].end);
}
}
return ans;
}
};

Editorial#

Common free time = complement of the union of busy intervals across all employees. Once you merge all intervals into the maximal busy timeline, the gaps between consecutive merged intervals are exactly the common free periods.

Complexity#

  • Time: O(n log n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.