LeetCode Solutions

759. Employee Free Time

Time: $O(n\log n)$

Space: $O(n)$

			

class Solution {
 public:
  vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {
    vector<Interval> ans;
    vector<Interval> intervals;

    for (const vector<Interval>& 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;
  }
};
			

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;
  }
}
			

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