Consolidate Overlapping Bookings in a Weekly Schedule
Greedy & IntervalsAuto-graded · 25 test casesLast updated
Parse weekday and 24-hour time strings, then merge touching or overlapping same-day bookings and output them in a canonical, sorted string format.
Consolidate Overlapping Bookings in a Weekly Schedule
You are given a list of bookings for a calendar week. Each booking is a pair of strings [start, end], and each string has the form:
"<Day> <H>:<MM>"
<Day>is one ofMon,Tue,Wed,Thu,Fri,Sat,Sun.- The time uses a 24-hour clock. The hour may be written with or without a leading zero (for example
9:00and09:00mean the same time), and the minutes always have two digits.
Both ends of a single booking fall on the same day, and the start is strictly earlier than the end.
Task
Combine bookings that overlap into single bookings.
- Two bookings overlap only if they are on the same day and their time ranges intersect. Ranges that merely touch also count:
9:00-13:00and13:00-14:00combine into9:00-14:00. - A booking contained entirely inside another is absorbed by it.
- Bookings on different days are never combined, even if their clock times coincide.
- Overlap is transitive: if A overlaps B and B overlaps C, all three become one booking.
- Duplicate bookings collapse into one.
Output format
Return a list of [start, end] string pairs for the combined bookings.
- Order the result by day of the week (
Monfirst,Sunlast), then by start time within a day. Do not order days alphabetically. - Write each time as
"<Day> <H>:<MM>"with no leading zero on the hour and a two-digit minute value. For example, the input"Tue 09:30"appears in the output as"Tue 9:30", and midnight appears as0:00. - If the input is empty, return an empty list.
Constraints
- Each booking's start and end are on the same day, with start strictly before end.
- No booking crosses midnight, and there is no wrap-around from Sunday to Monday.
- The input may be unsorted and may be large, so a solution better than O(n²) is expected.
- Times are valid 24-hour times.
Examples
Example 1
Input: consolidate_weekly_bookings([['Mon 9:00', 'Mon 13:00'], ['Mon 11:00', 'Mon 16:00']])
Output: [['Mon 9:00', 'Mon 16:00']]
Example 2
Input: consolidate_weekly_bookings([['Mon 9:00', 'Mon 13:00'], ['Mon 13:00', 'Mon 14:00']])
Output: [['Mon 9:00', 'Mon 14:00']]
Example 3
Input: consolidate_weekly_bookings([['Tue 09:30', 'Tue 10:30'], ['Mon 14:00', 'Mon 15:00'], ['Tue 10:00', 'Tue 12:00']])
Output: [['Mon 14:00', 'Mon 15:00'], ['Tue 9:30', 'Tue 12:00']]
Hints
Hint 1
Convert each time string to an integer (minutes since midnight) and each day to an index 0-6, so values compare numerically rather than as text.
Hint 2
If you sort the records as (day_index, start, end) tuples, bookings that could merge become neighbors, and one sort handles both the day order and the time order.
Hint 3
Sweep through the sorted list keeping the last combined booking. If the next one is on the same day and starts at or before the current end, extend the end with max(); otherwise begin a new booking.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is the standard merge-intervals pattern with a parsing and formatting layer around it.
- Parse. Turn each booking into a tuple
(day_index, start_minutes, end_minutes), whereMonis 0 throughSunis 6 and minutes count from midnight. Callingint()on the hour and minute parts handles optional leading zeros. Since both ends of a booking share a day, the day is stored once. - Sort. Tuples compare element by element, so one sort orders by day (Mon to Sun), then start, then end. Bookings on the same day become contiguous, and within a day they are in non-decreasing start order.
- Sweep. Keep a list of combined bookings. For each record, if the last combined booking is on the same day and
start <= last_end, extend its end tomax(last_end, end). Otherwise append the record as a new booking. Using<=makes touching endpoints merge, andmaxhandles a booking fully contained in the previous one. - Format. Convert minutes back with
divmod(minutes, 60)and print asH:MM, with no padding on the hour and two digits for the minutes.
Why it is correct
Consider the current record (s, e) and the last combined block [S, E] on the same day. Every record already merged into that block started at or before s.
- If
s <= E, the record touches or overlaps the block, so the union is exactly[S, max(E, e)]. - If
s > E, every later record on that day starts at or afters, so none can reach back to the block. It is final.
The day comparison prevents merging across days, even when a later day's start minute is smaller than an earlier day's end minute. Duplicates and chained overlaps are handled naturally because the running end only grows.
Complexity
- Time: O(n log n), dominated by the sort. Parsing, sweeping and formatting are each O(n).
- Space: O(n) for the parsed records and the output.
Reference solution
from typing import List
WEEK = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
WEEK_POS = {name: i for i, name in enumerate(WEEK)}
def consolidate_weekly_bookings(bookings: List[List[str]]) -> List[List[str]]:
records = []
for start_text, end_text in bookings:
day_name, start_clock = start_text.split()
_, end_clock = end_text.split()
sh, sm = map(int, start_clock.split(':'))
eh, em = map(int, end_clock.split(':'))
records.append((WEEK_POS[day_name], sh * 60 + sm, eh * 60 + em))
records.sort()
combined = []
for day, start, end in records:
if combined and combined[-1][0] == day and start <= combined[-1][2]:
last = combined[-1]
combined[-1] = (day, last[1], max(last[2], end))
else:
combined.append((day, start, end))
def fmt(minutes):
h, m = divmod(minutes, 60)
return f'{h}:{m:02d}'
result = []
for day, start, end in combined:
name = WEEK[day]
result.append([f'{name} {fmt(start)}', f'{name} {fmt(end)}'])
return result