Compute Free Windows from Schedule Constraints
Greedy & IntervalsAuto-graded · 21 test casesLast updated
Compute unreserved time windows for specified daily schedules given opening hours and existing bookings.
You are given daily operating hours and existing bookings for a service. Your task is to compute all free time intervals within operating hours for each day.
Input Format
hours: A dictionary mapping day names (e.g.,"Mon") to a pair[open_time, close_time].reservations: A dictionary mapping day names to a list of existing bookings[[start1, end1], [start2, end2], ...].
Times in hours and reservations can be specified as either HH:MM formatted strings (e.g., "11:00") or as integer minutes from midnight (e.g., 660).
Requirements & Behavior
- All time intervals are treated as half-open
[start, end). - If
close_time <= open_timefor a day, that day has no available slots (return an empty list[]). - Bookings must be clipped to the day's operating hours
[open_time, close_time]. Any block or portion of a block outside these hours should be ignored. - Existing bookings may be unsorted, overlap, or touch at boundaries (e.g., one ending at 13:00 and another starting at 13:00).
- Overlapping and adjacent reserved intervals must be merged before identifying free gaps.
- Only days present in the
hoursdictionary should appear in the returned dictionary. If a day is inhoursbut absent fromreservations, assume there are no bookings for that day. - Output times must be formatted as
HH:MMstrings with zero-padded two-digit hours and minutes.
Output Format
Return a dictionary matching each key in hours to a list of available [start_time, end_time] string pairs formatted as HH:MM.
Constraints
- $1 \le \text{len}(hours) \le 7$
- $0 \le \text{number of reservations per day} \le 10^4$
- Times are non-negative and bounded within a single day ($0 \le \text{minutes} \le 1440$ or
"00:00"to"24:00").
Examples
Example 1
Input: find_available_slots({'Mon': ['11:00', '22:00'], 'Tue': ['11:00', '22:00']}, {'Mon': [['12:00', '12:30'], ['18:00', '19:15']], 'Tue': []})
Output: {'Mon': [['11:00', '12:00'], ['12:30', '18:00'], ['19:15', '22:00']], 'Tue': [['11:00', '22:00']]}
Example 2
Input: find_available_slots({'Mon': ['09:00', '17:00']}, {'Mon': [['13:00', '14:00'], ['12:00', '13:30'], ['16:00', '17:00']]})
Output: {'Mon': [['09:00', '12:00'], ['14:00', '16:00']]}
Example 3
Input: find_available_slots({'Fri': [600, 1320], 'Sat': [720, 1440]}, {'Fri': [[660, 720], [720, 780], [900, 930]], 'Sat': [[1380, 1500]]})
Output: {'Fri': [['10:00', '11:00'], ['13:00', '15:00'], ['15:30', '22:00']], 'Sat': [['12:00', '23:00']]}
Hints
Hint 1
Convert all input timestamps (strings or integers) to unified integer minutes from midnight first.
Hint 2
Clip each reservation interval to [open_minutes, close_minutes] and ignore invalid intervals where start >= end.
Hint 3
Sort the clipped reservation intervals by start time and merge overlapping or adjacent intervals.
Hint 4
Use a sweep cursor starting at open_minutes to detect open gaps up to close_minutes, then format gaps back to HH:MM.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem requires finding unoccupied time ranges given opening hours and existing reservations.
- Normalization: Convert all input timestamps (whether
HH:MMstrings or integers) into standard integer minutes from midnight (h * 60 + m). - Clipping & Filtering: For each day, retrieve the opening time
open_mand closing timeclose_m. Ifclose_m <= open_m, the day has zero available time. Otherwise, process each reservation for that day by clipping its start time tomax(open_m, reservation_start)and its end time tomin(close_m, reservation_end). Keep only valid intervals whereclipped_start < clipped_end. - Merging Reserved Intervals: Sort the clipped intervals by start time. Iterate through them to merge overlapping or touching intervals (where
start <= last_end). - Gap Identification: Sweep a pointer (
cursor) starting fromopen_mtoclose_m. For each merged reserved block[start, end]:- If
cursor < start, the gap[cursor, start]represents free time. - Advance
cursortomax(cursor, end). - After reviewing all reserved blocks, if
cursor < close_m, add[cursor, close_m]as a final free window.
- If
- Formatting: Convert minute integer endpoints back into
HH:MMformatted strings usingf"{h:02d}:{m:02d}".
Complexity Analysis
- Time Complexity: $\mathcal{O}(N \log N)$ per day, where $N$ is the number of reservations for that day, driven by sorting the interval list. The merging and gap-sweeping passes run in $\mathcal{O}(N)$ linear time.
- Space Complexity: $\mathcal{O}(N)$ per day to store the clipped, merged, and formatted intervals.
from typing import Dict, List, Union
def find_available_slots(
hours: Dict[str, List[object]],
reservations: Dict[str, List[List[object]]]
) -> Dict[str, List[List[str]]]:
def to_minutes(val: Union[int, str]) -> int:
if isinstance(val, int):
return val
h, m = map(int, val.split(":"))
return h * 60 + m
def to_string(minutes: int) -> str:
h = minutes // 60
m = minutes % 60
return f"{h:02d}:{m:02d}"
result: Dict[str, List[List[str]]] = {}
for day, bounds in hours.items():
open_m = to_minutes(bounds[0])
close_m = to_minutes(bounds[1])
if close_m <= open_m:
result[day] = []
continue
raw_res = reservations.get(day, [])
clipped = []
for start_val, end_val in raw_res:
s = max(open_m, to_minutes(start_val))
e = min(close_m, to_minutes(end_val))
if s < e:
clipped.append((s, e))
clipped.sort()
merged = []
for s, e in clipped:
if not merged or s > merged[-1][1]:
merged.append([s, e])
else:
merged[-1][1] = max(merged[-1][1], e)
free_slots = []
cursor = open_m
for s, e in merged:
if cursor < s:
free_slots.append([to_string(cursor), to_string(s)])
cursor = max(cursor, e)
if cursor < close_m:
free_slots.append([to_string(cursor), to_string(close_m)])
result[day] = free_slots
return result