Skip to content

759. Employee Free Time 👍

  • Time: $O(n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {
    vector<Interval> ans;
    vector<Interval> intervals;

    for (const auto& s : schedule)
      intervals.insert(end(intervals), begin(s), end(s));

    sort(begin(intervals), end(intervals),
         [](const auto& a, const auto& b) { return a.start < b.start; });

    int prevEnd = intervals[0].end;

    for (const auto& [start, end] : intervals) {
      if (start > prevEnd)
        ans.emplace_back(prevEnd, start);
      prevEnd = max(prevEnd, end);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public List<Interval> employeeFreeTime(List<List<Interval>> schedule) {
    List<Interval> ans = new ArrayList<>();
    List<Interval> intervals = new ArrayList<>();

    schedule.forEach(s -> intervals.addAll(s));
    Collections.sort(intervals, (a, b) -> a.start - b.start);

    int prevEnd = intervals.get(0).end;

    for (Interval interval : intervals) {
      if (interval.start > prevEnd)
        ans.add(new Interval(prevEnd, interval.start));
      prevEnd = Math.max(prevEnd, interval.end);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]':
    ans = []
    intervals = []

    for s in schedule:
      intervals.extend(s)

    intervals.sort(key=lambda x: x.start)

    prevEnd = intervals[0].end

    for interval in intervals:
      if interval.start > prevEnd:
        ans.append(Interval(prevEnd, interval.start))
      prevEnd = max(prevEnd, interval.end)

    return ans