First Open Meeting Window Across All Employees
Greedy & IntervalsModel answerLast updated
Sweep merged busy intervals to find the earliest gap of a required duration that fits within every employee's working hours.
Scheduling a Group Meeting
You are building a calendar tool that suggests the earliest available meeting time for a group. Each person has a defined work window for the day and a set of times they are already committed.
Given that information, your job is to find the earliest moment t such that the block [t, t + d) fits entirely within every person's work window and does not collide with any of their existing commitments.
Inputs
find_first_open_slot(schedules, work_windows, d)
schedules: a list of lists.schedules[i]is a sorted, non-overlapping list of busy intervals for personi, each expressed as[start, end)in minutes from midnight.work_windows: a list of pairs[start, end)in minutes from midnight, one per person.d: the required meeting length in minutes.
Return the earliest valid start time t, or -1 if no such block exists within a single day (minutes 0 to 1440).
Example
schedules = [[[100, 200]], [[150, 250]]]
work_windows = [[0, 500], [0, 500]]
d = 60
# Output: 0
# [0, 60) is free for everyone and falls inside both work windows.
Constraints
0 <= d <= 1440- Each person's busy list is already sorted with no overlapping entries.
- Up to 1,000 people.
- Total busy intervals across all people is
M. - Intervals are half-open:
[start, end)means the minuteendis free.
What is expected
Walk through your approach before coding. Explain how you handle the shift intersection, how you merge intervals from multiple people efficiently, and cover edge cases. Include a time and space complexity analysis.
Hints
Hint 1
Before looking at busy times at all, figure out the range of minutes where a meeting is even legal. A slot outside any one person's work window is automatically invalid — what does that mean for the combined valid range?
Hint 2
You don't need to know who is busy, only whether anyone is. Think about what structure lets you sweep all busy intervals in time order without flattening them into a single list first.
Hint 3
Track a single 'cursor' representing the earliest minute that is still a candidate start. When you encounter a busy block, ask: is there a gap before it wide enough? If not, how far forward should the cursor jump?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem splits cleanly into two independent sub-problems.
Step 1 — Find the common work window
A meeting must fit inside every person's shift. The valid range is the intersection of all shifts:
lo = max of all shift starts
hi = min of all shift ends
Any minute outside [lo, hi) is blocked for at least one person. Computing this is O(N) and avoids injecting fake busy intervals for non-working hours.
If lo + d > hi (the window is narrower than the meeting), return -1 immediately.
Step 2 — Sweep the merged busy intervals
Now find the earliest gap of width at least d inside [lo, hi) across the union of all busy intervals. You do not need to materialize the merged union — a cursor is enough.
Keep cursor = lo (the earliest candidate start seen so far). Pull intervals in start-time order using a k-way heap merge over the N already-sorted lists. For each interval [start, end):
- Skip it if
end <= cursor— it is already behind the candidate. - Stop if
start >= hi— everything remaining is outside the window. - Return
cursorifstart - cursor >= d— the gap fits. - Advance
cursor = max(cursor, end)and continue.
After the loop, check the final gap: return cursor if cursor + d <= hi, else -1.
The cursor implicitly tracks the end of the current merged busy block. max(cursor, end) handles nested or touching intervals from different people correctly.
Why it's correct
Invariant: before processing interval k (in start order), every t in [lo, cursor) has been ruled out — it either falls inside a busy block or starts a gap shorter than d.
When a gap [cursor, start) is at least d wide, no unseen interval begins before start (we process in order), so the gap is genuinely free for everyone. By the invariant, cursor is also the earliest such point.
Advancing past a short gap is safe: any t in [cursor, end) either falls inside the current busy block or would produce a meeting [t, t+d) that overlaps it.
Edge cases
- Disjoint shifts (
lo > hi): return -1 before touching any busy intervals. d == 0: an empty meeting overlaps nothing; returnlo.- Busy intervals outside
[lo, hi): the skip and stop rules handle them without special-casing. - Nested intervals across people (e.g.,
[100, 300)and[150, 200)):max(cursor, end)never moves the cursor backward. - No employees: defaults give
lo = 0,hi = 1440; return 0 for anyd <= 1440. - Empty busy lists: those people contribute only through their shift intersection.
Complexity
- Time: O(N + M log N) — O(N) for the shift intersection, O(M log N) for the heap merge (one push/pop per interval). A flat sort instead gives O(M log M), which is fine too but doesn't exploit the pre-sorted guarantee.
- Space: O(N) for the heap.
heapq.mergeis lazy; it never loads all M intervals at once.
Python solution
import heapq
from typing import List
def find_first_open_slot(
schedules: List[List[List[int]]],
work_windows: List[List[int]],
d: int,
) -> int:
DAY = 1440
# Intersection of all work windows, clipped to the day.
lo = max([0] + [s for s, _ in work_windows])
hi = min([DAY] + [e for _, e in work_windows])
if lo > hi:
return -1
if d == 0:
return lo # empty meeting always fits
if lo + d > hi:
return -1
cursor = lo
# k-way merge: O(M log N), exploits the sorted guarantee.
for start, end in heapq.merge(*schedules, key=lambda iv: iv[0]):
if end <= cursor:
continue # already past this block
if start >= hi:
break # beyond the common window
if start - cursor >= d:
return cursor # gap [cursor, start) fits
cursor = max(cursor, end)
if cursor + d > hi:
return -1 # no room left
return cursor if cursor + d <= hi else -1
Traced example
schedules = [[[100, 200]], [[150, 250]]], work_windows = [[0, 500], [0, 500]], d = 60
lo = 0,hi = 500. Window is 500 min wide;d = 60fits.cursor = 0.- First interval:
[100, 200). Gap =100 - 0 = 100 >= 60. Return 0.
With d = 120:
[100, 200): gap = 100 < 120, socursor = 200.[150, 250):end = 250 > cursor,start = 150 < cursor, socursor = max(200, 250) = 250.- Loop ends. Final gap =
500 - 250 = 250 >= 120. Return 250.
Common mistakes
- Using
>instead of>=in the gap check — this rejects meetings of exactly lengthd, which are valid because intervals are half-open. - Forgetting
max(cursor, end)when advancing — without it, a short nested interval from a second person can move the cursor backward. - Skipping the
lo > higuard and letting a negative-width window produce false positives. - Sorting all intervals together (O(M log M)) without mentioning the heap merge — correct, but misses the opportunity to use the pre-sorted property.
Follow-up directions
Difference array alternative (when M is large and the domain is small): build a length-1441 array, add +1 at each busy start and -1 at each end, prefix-sum it, then scan for the first run of d consecutive zeros inside [lo, hi). This is O(N + M + 1440) with no heap and simpler code — a good trade when N is huge but the time domain stays 1,440 minutes.
Time zones: normalize everything to UTC at ingestion. A "day" may be 1,380 or 1,500 minutes on DST boundaries. Store instants in UTC and convert to local only for display. Per-user time zones mean each person's [lo, hi) must be computed independently in UTC before taking the intersection.
Real-time updates: maintain an interval tree or a segment tree over the day's minutes (with augmented fields for the longest free run). Calendar change events update the structure in O(log T) per event, so a re-query costs O(log T) rather than a full re-sweep.