KatInterview

761. Employee Free Time

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the common free time for a group of employees, given their individual work schedules. Each employee's schedule consists of a list of sorted, non-overlapping time intervals. The goal is to identify the time intervals where all employees are simultaneously free.

Solution

Employee Free Time in Python

"""
# Definition for an Interval.
class Interval:
    def __init__(self, start: int = None, end: int = None):
        self.start = start
        self.end = end
"""

class Solution:
    def employeeFreeTime(self, schedule: '[[Interval]]') -> '[Interval]':
        # Step 1: Flatten the schedule into a single list of intervals.
        all_intervals = []
        for emp_schedule in schedule:
            all_intervals.extend(emp_schedule)
        
        if not all_intervals:
            return []

        # Step 2: Sort all intervals based on their start time.
        all_intervals.sort(key=lambda x: x.start)
        
        result = []
        # Initialize busy_until with the end time of the first interval.
        busy_until = all_intervals[0].end
        
        # Step 3: Iterate through the sorted intervals to find gaps.
        for i in range(1, len(all_intervals)):
            current_interval = all_intervals[i]
            # If the current interval starts after the last busy time, we found a free time gap.
            if current_interval.start > busy_until:
                result.append(Interval(busy_until, current_interval.start))
            
            # Update the end of the busy period to cover the current interval.
            busy_until = max(busy_until, current_interval.end)
            
        return result

Employee Free Time in Java

/*
// Definition for an Interval.
class Interval {
    public int start;
    public int 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> allIntervals = new ArrayList<>();
        // Step 1: Flatten the schedule into a single list of intervals.
        for (List<Interval> empSchedule : schedule) {
            allIntervals.addAll(empSchedule);
        }
        
        if (allIntervals.isEmpty()) {
            return new ArrayList<>();
        }

        // Step 2: Sort all intervals based on their start time.
        allIntervals.sort((a, b) -> a.start - b.start);

        List<Interval> result = new ArrayList<>();
        // Initialize busyUntil with the end time of the first interval.
        int busyUntil = allIntervals.get(0).end;

        // Step 3: Iterate through the sorted intervals to find gaps.
        for (int i = 1; i < allIntervals.size(); i++) {
            Interval currentInterval = allIntervals.get(i);
            // If the current interval starts after the last busy time, we found a free time gap.
            if (currentInterval.start > busyUntil) {
                result.add(new Interval(busyUntil, currentInterval.start));
            }
            // Update the end of the busy period to cover the current interval.
            busyUntil = Math.max(busyUntil, currentInterval.end);
        }

        return result;
    }
}

Employee Free Time in C++

/*
// Definition for an Interval.
class Interval {
public:
    int start;
    int end;

    Interval() {}

    Interval(int _start, int _end) {
        start = _start;
        end = _end;
    }
};
*/

class Solution {
public:
    vector<Interval> employeeFreeTime(vector<vector<Interval>> schedule) {
        vector<Interval> all_intervals;
        // Step 1: Flatten the schedule into a single list of intervals.
        for (const auto& emp_schedule : schedule) {
            for (const auto& interval : emp_schedule) {
                all_intervals.push_back(interval);
            }
        }

        if (all_intervals.empty()) {
            return {};
        }

        // Step 2: Sort all intervals based on their start time.
        sort(all_intervals.begin(), all_intervals.end(), [](const Interval& a, const Interval& b) {
            return a.start < b.start;
        });

        vector<Interval> result;
        // Initialize busy_until with the end time of the first interval.
        int busy_until = all_intervals[0].end;

        // Step 3: Iterate through the sorted intervals to find gaps.
        for (size_t i = 1; i < all_intervals.size(); ++i) {
            const Interval& current_interval = all_intervals[i];
            // If the current interval starts after the last busy time, we found a free time gap.
            if (current_interval.start > busy_until) {
                result.push_back(Interval(busy_until, current_interval.start));
            }
            // Update the end of the busy period to cover the current interval.
            busy_until = max(busy_until, current_interval.end);
        }

        return result;
    }
};

Employee Free Time in TypeScript

/**
 * // Definition for an Interval.
 * class Interval {
 *    start: number;
 *    end: number;
 *    constructor(start: number, end: number) {
 *        this.start = start;
 *        this.end = end;
 *    }
 * }
 */

function employeeFreeTime(schedule: Interval[][]): Interval[] {
    // Step 1: Flatten the schedule into a single list of intervals.
    const allIntervals = schedule.flat();

    if (allIntervals.length === 0) {
        return [];
    }

    // Step 2: Sort all intervals based on their start time.
    allIntervals.sort((a, b) => a.start - b.start);

    const result: Interval[] = [];
    // Initialize busyUntil with the end time of the first interval.
    let busyUntil = allIntervals[0].end;

    // Step 3: Iterate through the sorted intervals to find gaps.
    for (let i = 1; i < allIntervals.length; i++) {
        const currentInterval = allIntervals[i];
        // If the current interval starts after the last busy time, we found a free time gap.
        if (currentInterval.start > busyUntil) {
            result.push(new Interval(busyUntil, currentInterval.start));
        }
        // Update the end of the busy period to cover the current interval.
        busyUntil = Math.max(busyUntil, currentInterval.end);
    }

    return result;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.