Open Half-Hour Slots from Weekly Hours and Bookings
Greedy & IntervalsAuto-graded · 19 test casesLast updated
Expand a weekly schedule over a date range and subtract booked intervals to list every free, half-hour-aligned 30-minute slot in chronological order.
Open Half-Hour Slots
A practice owner publishes a weekly template of working hours. Some time ranges are already booked. Given a range of calendar dates, list every 30-minute slot that is still free.
Inputs
weekly_hours: a dictionary mapping a weekday key to a list of working windows.- Keys are strings:
"0"is Monday,"1"is Tuesday, ...,"6"is Sunday. - Each window is
[start, end], with both times as"HH:MM"strings on a 24-hour clock. - A weekday with no key has no working hours.
- Keys are strings:
bookings: a list of[start, end]pairs. Each is a datetime string in the formYYYY-MM-DDTHH:MM:SS.range_start,range_end: ISO dates (YYYY-MM-DD). Both are inclusive.
Task
Return all free slots, where each slot is a two-element list [slot_start, slot_end] of strings in YYYY-MM-DDTHH:MM:SS format.
For each date from range_start to range_end, take the windows listed for that date's weekday. A window is interpreted on that same date.
A slot is returned when all of these hold:
- It lasts exactly 30 minutes.
- It lies completely inside one working window, so the slot start is no earlier than the window start and the slot end is no later than the window end.
- Its start minute is
00or30. - It is not blocked by any booking.
Rules
- Slot placement inside a window. The first slot in a window starts at the window's start time if that is already on
:00or:30. Otherwise it starts at the next:00or:30after it. Later slots follow back-to-back, 30 minutes apart. Any leftover time shorter than 30 minutes at the end of a window is unused. For example,09:15–10:00yields only09:30–10:00. - Blocking. A booking
[b_start, b_end]blocks a slot[s, e]exactly whenb_start < eandb_end > s. Intervals that merely touch do not block. A booking ending at 09:30 does not block the slot starting at 09:30. - Bookings may be given in any order, may overlap each other, and may fall on dates outside the range, in which case they have no effect. A booking may cross the edges of a working window.
- A window whose end is not later than its start is ignored.
- If
range_startis later thanrange_end, return an empty list. - The result must be sorted chronologically by slot start.
Constraints
- All times in
weekly_hoursare valid"HH:MM"values from"00:00"to"23:59". - Windows listed for the same weekday do not overlap one another.
- The date range spans at most a few hundred days, so each date can be handled one at a time.
- The total number of bookings is at most a few thousand.
- Dates and datetimes are valid ISO strings. Booking times have no time-zone information.
Examples
Example 1
Input: list_open_slots({'0': [['09:00', '10:00']]}, [['2023-10-02T09:30:00', '2023-10-02T10:00:00']], '2023-10-02', '2023-10-02')
Output: [['2023-10-02T09:00:00', '2023-10-02T09:30:00']]
Example 2
Input: list_open_slots({'0': [['09:00', '11:00']]}, [], '2023-10-02', '2023-10-02')
Output: [['2023-10-02T09:00:00', '2023-10-02T09:30:00'], ['2023-10-02T09:30:00', '2023-10-02T10:00:00'], ['2023-10-02T10:00:00', '2023-10-02T10:30:00'], ['2023-10-02T10:30:00', '2023-10-02T11:00:00']]
Hints
Hint 1
Walk through the dates one day at a time and use the date's weekday to look up that day's working windows.
Hint 2
Round each window's start up to the next multiple of 30 minutes, then step forward 30 minutes at a time while the whole slot still fits before the window end.
Hint 3
A slot is blocked only if a booking starts before the slot ends and ends after the slot starts. Sorting the bookings by start lets you stop checking early once a booking starts at or after the slot's end.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Walk the dates. Loop from
range_starttorange_endinclusive. If the start is after the end, the loop never runs and the result is empty. - Expand the template. For each date,
weekday()selects the windows fromweekly_hours(keys are strings). Each window is converted to minutes since midnight. Windows whose end is not after their start are skipped. - Align the start. Round the window start up to the next multiple of 30 minutes with
ceil(start / 30) * 30. This leaves:00and:30unchanged and moves anything else to the next half hour. - Generate candidate slots. Starting at the aligned time, step forward 30 minutes at a time while
slot_start + 30 min <= window_end. This drops any trailing remainder shorter than 30 minutes. - Test against bookings. Sort the bookings by start time once. A slot
[s, e)is blocked iff some booking hasb_start < eandb_end > s. Scanning the sorted list, stop as soon as a booking starts at or aftere, since all later bookings start even later. Otherwise a booking withb_end > sblocks the slot. - Sort the output. Slots are produced in date order and window order. A final sort guarantees chronological order even if windows in the template were listed out of order.
Why it is correct
- Every returned slot lies inside a working window, starts on a half-hour boundary, is 30 minutes long, and overlaps no booking, so it is valid.
- Every valid slot starts on a half-hour boundary at or after the window start, so it is one of the aligned candidates generated by stepping from the first aligned point. Each candidate is accepted exactly when no booking overlaps it, so no valid slot is missed.
- Using strict inequalities in the overlap test means intervals that only touch (such as a booking ending exactly when the slot starts) do not block, which is the specified rule.
- Because windows for one weekday do not overlap, no slot is generated twice.
Complexity
Let D be the number of days, W the number of windows per day, B the number of bookings, and S the number of candidate slots, which is at most D * W * 48.
- Time: O(B log B + S * B) in the worst case for the simple scan. The early break makes it much faster in practice, and a pointer sweep over the sorted bookings would bring the check down to O(B log B + S).
- Space: O(B + S).
Reference solution
from datetime import date, datetime, timedelta
from typing import Dict, List
def list_open_slots(weekly_hours: Dict[str, List[List[str]]], bookings: List[List[str]], range_start: str, range_end: str) -> List[List[str]]:
first = date.fromisoformat(range_start)
last = date.fromisoformat(range_end)
step = timedelta(minutes=30)
busy = sorted(
(datetime.fromisoformat(s), datetime.fromisoformat(e))
for s, e in bookings
)
result = []
day = first
while day <= last:
midnight = datetime(day.year, day.month, day.day)
for start_text, end_text in weekly_hours.get(str(day.weekday()), []):
sh, sm = map(int, start_text.split(":"))
eh, em = map(int, end_text.split(":"))
start_min = sh * 60 + sm
end_min = eh * 60 + em
if end_min <= start_min:
continue
# round the start up to the next multiple of 30 minutes
aligned = -(-start_min // 30) * 30
window_end = midnight + timedelta(minutes=end_min)
slot_start = midnight + timedelta(minutes=aligned)
while slot_start + step <= window_end:
slot_end = slot_start + step
free = True
for b_start, b_end in busy:
if b_start >= slot_end:
break
if b_end > slot_start:
free = False
break
if free:
result.append([slot_start.isoformat(timespec="seconds"),
slot_end.isoformat(timespec="seconds")])
slot_start = slot_end
day += timedelta(days=1)
result.sort()
return result