Employee Free Time solution explained
Employee Free Time gives you each person's working hours as a sorted list of non-overlapping intervals and asks for the finite stretches when nobody is working. Read all the intervals in order of start time, either by sorting them together or by merging the k sorted lists with a min-heap, and track the latest end seen so far: whenever the next interval starts after that end, the space between them is shared free time. Sorting costs O(N log N) for N intervals in total; the heap merge costs O(N log k) for k employees.
By Evin JohnPublished 7 min read
The problem, restated
You have a team of k people. For each person you get a list of [start, end] shifts, sorted by start, with no two shifts of the same person overlapping. Return every interval of positive length during which nobody on the team is working, sorted by start. Gaps that run to minus or plus infinity are left out, and two shifts that touch, such as one ending at 5 and another starting at 5, leave no gap.
On a judge site this problem often arrives with a custom interval object. In an interview, agree on plain pairs unless you are told otherwise; it keeps the code short and the idea is the same.
| Schedules | Shared free time | Why |
|---|---|---|
| [[[1, 3], [9, 10]], [[2, 4], [6, 7]], [[12, 14]]] | [[4, 6], [7, 9], [10, 12]] | Busy time merges to 1-4, 6-7, 9-10, 12-14 |
| [[[1, 5]], [[5, 8]]] | [] | The shifts touch at 5, so there is no gap |
| [[[0, 2], [4, 6]]] | [[2, 4]] | One person: their own breaks |
| [[[3, 4]], [[1, 10]]] | [] | One long shift covers the other |
| [[[8, 9]], [[1, 2]]] | [[2, 8]] | Schedules do not arrive in time order across people |
What the interviewer is looking for
The core move is the one from merging intervals: once all busy intervals are in start order, you only need to remember how far the busy time reaches. What separates answers is whether you use the fact that each person's list is already sorted. A candidate who says "flatten and sort" gets a working O(N log N) solution; one who then says "each list is sorted, so I can merge them like k sorted lists with a heap" shows they read the input carefully. Interviewers also check that you leave out the infinite ends and the zero-length gaps.
Clarifying questions
- Do touching shifts leave a gap? Usually not: free time must have positive length.
- Should the open ends count? No, only finite gaps between the first and last busy moment.
- Can a person have no shifts? Then they never block anything, so they can be skipped.
- How big is k compared with N? If k is small, the heap merge is close to linear.
A simple start: mark every hour
If times are small integers, you could mark each unit of time as busy in an array and then read off the runs of free units between the first and last busy unit. It is easy to reason about but depends on the size of the time range rather than on the number of shifts, so it falls apart for timestamps in seconds or minutes across a year. Mention it as a sanity check and move on.
Flatten, sort, sweep
Put every shift from every person into one list and sort it by start. Walk the list with a variable reach holding the largest end seen so far. If the next shift starts after reach, the stretch from reach to that start is free for everyone: nobody's shift that started earlier lasts past reach, and nobody's shift starts before this one. Record the gap, then extend reach to the larger of itself and the current end.
def free_time_sorted(schedules):
shifts = sorted(s for person in schedules for s in person)
gaps = []
if not shifts:
return gaps
reach = shifts[0][1]
for start, end in shifts[1:]:
if start > reach:
gaps.append([reach, start])
reach = max(reach, end)
return gapsfunction employeeFreeTime(schedules) {
const shifts = schedules.flat().sort((a, b) => a[0] - b[0]);
const gaps = [];
if (shifts.length === 0) return gaps;
let reach = shifts[0][1];
for (let i = 1; i < shifts.length; i++) {
const [start, end] = shifts[i];
if (start > reach) gaps.push([reach, start]);
reach = Math.max(reach, end);
}
return gaps;
}The test is start > reach, strictly. A shift that starts exactly at reach continues the busy time without a break, which is what keeps [[1, 5]] and [[5, 8]] from producing an empty gap [5, 5].
Using the sorted lists: a k-way heap merge
Each person's shifts are already in order, so the global order can be produced the way you merge k sorted lists. Put the first shift of every person into a min-heap keyed by start. Pop the smallest, process it with the same reach logic, and push that person's next shift. The heap never holds more than k entries, so each of the N pops and pushes costs O(log k).
import heapq
def free_time_heap(schedules):
heap = [(person[0][0], p, 0) for p, person in enumerate(schedules) if person]
heapq.heapify(heap)
gaps = []
reach = None
while heap:
start, p, idx = heapq.heappop(heap)
end = schedules[p][idx][1]
if reach is not None and start > reach:
gaps.append([reach, start])
reach = end if reach is None else max(reach, end)
if idx + 1 < len(schedules[p]):
heapq.heappush(heap, (schedules[p][idx + 1][0], p, idx + 1))
return gapsThe heap entries carry the person index and the position in their list, not the shift itself, so ties on start compare small integers and nothing else. That keeps the comparison cheap and avoids comparing lists in Python.
Trace on the first example
| Shift | reach before | Gap recorded | reach after |
|---|---|---|---|
| [1, 3] | none | none | 3 |
| [2, 4] | 3 | none (2 is not past 3) | 4 |
| [6, 7] | 4 | [4, 6] | 7 |
| [9, 10] | 7 | [7, 9] | 10 |
| [12, 14] | 10 | [10, 12] | 14 |
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Mark every unit of time | O(N + T) plus the cost of marking each shift's length | O(T) |
| Flatten, sort, sweep | O(N log N) | O(N) for the flat list |
| Heap merge, then sweep | O(N log k) | O(k) for the heap |
When k is 1 the heap version is linear, and when every person has a single shift the two approaches are the same. The difference matters when a handful of people each have long schedules.
Edge cases
- Everyone has an empty schedule: return an empty list, and make sure the code does not read shifts[0].
- A single employee: the answer is just the breaks in their own schedule.
- Shifts that touch across people, such as [1, 5] and [5, 8]: no gap.
- One person's long shift swallowing several of another's: reach must take the max, not the latest end.
- Zero-length shifts like [4, 4]: they count as busy at that instant, so they can split one free stretch into two.
Common mistakes
- Setting reach to the current end instead of max(reach, end). A short shift inside a long one would then open a false gap.
- Using start >= reach, which reports zero-length gaps between touching shifts.
- Reporting the time before the first shift or after the last one.
- Merging each person's schedule with the next one pairwise and recomputing from scratch every time, which hides an O(N × k) cost.
- In JavaScript, sorting without a comparator, which compares the pairs as strings.
How to explain it out loud
Fictional example
- Candidate
- Free time for everyone is the complement of the union of all busy shifts, restricted to between the first and last shift. So I need the union, which means processing shifts in start order.
- Candidate
- The simple version flattens and sorts. Then I keep the furthest end I have seen, and any start beyond it gives me a gap from that end to the start.
- Interviewer
- Can you do better than sorting everything?
- Candidate
- Each person's list is already sorted, so I can merge them with a heap of size k, one entry per person. That makes it N log k. The sweep logic stays the same.
Related problems
Merge Intervals builds the union this page sweeps over; the free time is what lies between its output intervals. Merge k Sorted Lists is the same heap merge on linked lists. Interval List Intersections asks when two people are both busy rather than when everyone is free, and Process Tasks Using Servers uses a heap of finishing times to decide who is free next.
Practicing with Natively
This problem rewards one clear sentence before any code: free time is the gaps in the union of busy time. Rehearse that sentence in a mock round. Natively, on Mac or Windows, transcribes the session so you can check whether you said it, and after your own attempt it can read the problem from a screenshot and offer an approach, such as the heap merge, to compare with what you wrote. See the AI interview assistant for how practice sessions work.
Questions people ask
How do you solve Employee Free Time?
Process every shift in order of start time while tracking the latest end seen. When a shift starts after that end, the stretch between them is free for everyone. Sort all shifts together, or merge the sorted schedules with a heap.
Why use a heap for Employee Free Time?
Each employee's schedule is already sorted, so a min-heap holding one shift per employee yields all shifts in start order in O(N log k) instead of O(N log N) for a full sort.
Do touching shifts create free time?
No. If one shift ends at 5 and another starts at 5, there is no gap of positive length, so compare with start > end, not start >= end.
Is time before the first shift free time?
Not in this problem. Only finite gaps between the earliest start and the latest end are returned.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
