SDE & MLE Prep

759. Employee Free Time

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