Merge Weekly Schedule Intervals
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
A weekly calendar stores busy blocks as two-element string lists [start_time, end_time]. Every timestamp uses 24-hour clock notation in the form "<Day> <H>:<MM>", where <Day> is one of the seven three-letter weekday codes (Mon, Tue, Wed, Thu, Fri, Sat, Sun). Input hours may appear with or without a leading zero (such as "8:15" or "08:15"), while minutes always contain two digits ("00" through "59").
Each individual block begins and ends on the same weekday with start_time strictly earlier than end_time. Two blocks on the same weekday must be combined whenever their time ranges overlap or touch at an endpoint — for instance, a window ending at 12:30 and another starting at 12:30 on the same day fuse into one continuous window. Blocks on different weekdays never combine.
Implement merge_overlapping_intervals(intervals) to return the consolidated schedule sorted chronologically from Mon through Sun, and by ascending start time within each day. Format every returned timestamp as "<Day> <H>:<MM>" with no leading zero on the hour and two digits for the minute.
Examples
Example 1
Input: intervals = [["Wed 8:30", "Wed 11:00"], ["Wed 10:15", "Wed 13:45"]]
Output: [["Wed 8:30", "Wed 13:45"]]
Both blocks take place on Wednesday, and 10:15 starts before 11:00 finishes, so they merge into a single block from 8:30 to 13:45.
Example 2
Input: intervals = [["Thu 10:00", "Thu 12:30"], ["Thu 12:30", "Thu 15:15"]]
Output: [["Thu 10:00", "Thu 15:15"]]
The first Thursday session ends right at 12:30, which is the exact start of the second Thursday session. Touching endpoints on the same day count as overlapping and combine into one span.
Example 3
Input: intervals = [["Fri 08:15", "Fri 09:45"], ["Tue 16:00", "Tue 17:30"], ["Fri 9:30", "Fri 11:20"]]
Output: [["Tue 16:00", "Tue 17:30"], ["Fri 8:15", "Fri 11:20"]]
Tuesday comes before Friday in calendar order. The two Friday blocks overlap between 9:30 and 9:45, merging into ["Fri 8:15", "Fri 11:20"] with the leading zero stripped from "08:15".
Constraints
0 <= len(intervals) <= 10^5- Each element
intervals[i]is a two-item list[start_time, end_time]on the same weekday (Mon,Tue,Wed,Thu,Fri,Sat, orSun). - Every timestamp represents a valid 24-hour clock time from
0:00through23:59, withstart_timestrictly beforeend_time. - Your algorithm should run faster than
O(n^2)time on large inputs.
Step-by-step walkthrough
Restate the problem and format rules
Each calendar block is a two-element list
[start_str, end_str]such as["Fri 08:15", "Fri 09:45"]:<Day>is one ofMon, Tue, Wed, Thu, Fri, Sat, Sun.<H>:<MM>is a 24-hour clock value; input hours may or may not include a leading zero ("8:30"or"08:15").- Every block begins strictly before it ends (
start < end), with both timestamps on the same weekday.
We need to combine overlapping windows within each day and return them ordered from
MonthroughSun, then by start time:- Touching endpoints merge:
["Thu 10:00", "Thu 12:30"]and["Thu 12:30", "Thu 15:15"]combine into["Thu 10:00", "Thu 15:15"]. - Different days never merge:
["Mon 22:00", "Mon 23:59"]and["Tue 0:00", "Tue 1:00"]remain separate. - Output string normalization: in Example 3,
"Fri 08:15"becomes"Fri 8:15", so formatted hours have no leading zero while minutes always use two digits (8:05,16:00).
Why raw string comparison and pairwise merging fail
First, sorting or comparing raw strings gives the wrong calendar and clock order:
Alphabetical (wrong) Chronological (right) "Fri 8:15" < "Tue 16:00" Tue comes before Fri "Sat 10:00" < "Sat 9:30" 9:30 comes before 10:00 ('1' < '9' in ASCII!)Second, even after converting timestamps to numbers, repeatedly scanning the list to find any overlapping pair and merging it takes
O(n^2)checks per pass (and up toO(n^3)acrossn - 1merges), which is far too slow whennreaches10^5.Turn strings into `(day_index, minutes_since_midnight)`
Mapping
Mon..Sunto0..6and convertingH:MMintoH * 60 + MMminutes since midnight turns every timestamp into a pair of plain integers that compare in true calendar order:"Tue 16:00" -> day_index = 1, total_minutes = 16 * 60 + 0 = 960 "Fri 08:15" -> day_index = 4, total_minutes = 8 * 60 + 15 = 495 "Fri 11:20" -> day_index = 4, total_minutes = 11 * 60 + 20 = 680int("08")andint("8")both evaluate to8, stripping leading zeros automatically during parsing. Formatting back into text uses integer division (total_minutes // 60) for the hour and modulo (total_minutes % 60) with:02dso5minutes prints as"05".# Ordered weekday names so index 0..6 matches Monday..Sunday. DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] # DAY_TO_INDEX: maps weekday string -> week order index, e.g. {"Mon": 0, ..., "Sun": 6}. DAY_TO_INDEX = {day_name: index for index, day_name in enumerate(DAYS)} def parse_time(text: str) -> Tuple[int, int]: """Convert e.g. 'Fri 08:15' -> (4, 495): (day_index, minutes_since_midnight).""" day_name, clock = text.split() hour_text, minute_text = clock.split(":") total_minutes = int(hour_text) * 60 + int(minute_text) return DAY_TO_INDEX[day_name], total_minutes def format_time(day_index: int, total_minutes: int) -> str: """Convert e.g. (4, 495) -> 'Fri 8:15': no leading zero on hour, 2-digit minute.""" hour = total_minutes // 60 minute = total_minutes % 60 return f"{DAYS[day_index]} {hour}:{minute:02d}"Key idea: sort once, then sweep left to right
Store each window as
(day_index, start_min, end_min)and sort the list. Python compares tuples element by element: first byday_index(0..6), then bystart_min, then byend_min.Once windows are sorted by start time within each day, we only ever need to compare the next window against the most recently merged block:
Case 1 — Overlap: [8:30 -------- 11:00] [10:15 -------- 13:45] -> [8:30 -------------- 13:45] Case 2 — Touching: [10:00 ------- 12:30] [12:30 - 15:15] -> [10:00 --------- 15:15] Case 3 — Contained: [9:00 ---------------- 17:00] [10:00 - 11:00] -> [9:00 ---------------- 17:00] Case 4 — Gap / New day: [9:00 - 10:00] [10:01 - 11:00] -> keep separate, start new blockWhy can't an incoming window skip past the last block and overlap an earlier block? Because the earlier block already ended strictly before the last block began, and every later window starts at or after the last block's start!
Code the sort, merge sweep, and formatting
Watch two subtle details in the sweep:
- Check
start_min <= merged[-1][2]with<=(not<) so touching endpoints combine. - Extend the block's end with
max(merged[-1][2], end_min)(not= end_min) so Case 3 above never shrinks[9:00, 17:00]down to[9:00, 11:00].
def merge_overlapping_intervals(intervals: List[List[str]]) -> List[List[str]]: # Phase 1: Parse strings into comparable (day_index, start_min, end_min) tuples # and sort chronologically by day (Mon..Sun), then by start time. parsed = [] for start_text, end_text in intervals: day_index, start_min = parse_time(start_text) _, end_min = parse_time(end_text) parsed.append((day_index, start_min, end_min)) parsed.sort() # Phase 2: Sweep through sorted blocks and merge overlapping same-day windows. # merged: list of mutable [day_index, start_min, end_min] blocks, e.g. [[2, 510, 825]]. merged: List[List[int]] = [] for day_index, start_min, end_min in parsed: # Use '<=' because touching endpoints (e.g. 12:30 and 12:30) count as overlapping. if merged and merged[-1][0] == day_index and start_min <= merged[-1][2]: # Take max() so a shorter window nested inside a longer one does not shrink it. merged[-1][2] = max(merged[-1][2], end_min) else: merged.append([day_index, start_min, end_min]) # Phase 3: Format each merged numeric block back into '<Day> <H>:<MM>' strings. result = [] for day_index, start_min, end_min in merged: result.append([format_time(day_index, start_min), format_time(day_index, end_min)]) return result- Check
Trace Example 3 step by step
Input:
[["Fri 08:15", "Fri 09:45"], ["Tue 16:00", "Tue 17:30"], ["Fri 9:30", "Fri 11:20"]]Step Action / Item State of data ---- ------------------ --------------------------------------------- Parse Fri 08:15 - 09:45 (4, 495, 585) Tue 16:00 - 17:30 (1, 960, 1050) Fri 9:30 - 11:20 (4, 570, 680) Sort by (day, start) [(1, 960, 1050), (4, 495, 585), (4, 570, 680)] Sweep (1, 960, 1050) merged = [[1, 960, 1050]] (first block) (4, 495, 585) merged = [[1, 960, 1050], (day 4 != day 1 -> new block) [4, 495, 585]] (4, 570, 680) 570 <= 585 on day 4 -> extend end to max(585, 680) = 680 merged = [[1, 960, 1050], [4, 495, 680]] Format [["Tue 16:00", "Tue 17:30"], ["Fri 8:15", "Fri 11:20"]]Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple # Ordered weekday names so index 0..6 matches Monday..Sunday. DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] # DAY_TO_INDEX: maps weekday string -> week order index, e.g. {"Mon": 0, ..., "Sun": 6}. DAY_TO_INDEX = {day_name: index for index, day_name in enumerate(DAYS)} def parse_time(text: str) -> Tuple[int, int]: """Convert e.g. 'Fri 08:15' -> (4, 495): (day_index, minutes_since_midnight).""" day_name, clock = text.split() hour_text, minute_text = clock.split(":") total_minutes = int(hour_text) * 60 + int(minute_text) return DAY_TO_INDEX[day_name], total_minutes def format_time(day_index: int, total_minutes: int) -> str: """Convert e.g. (4, 495) -> 'Fri 8:15': no leading zero on hour, 2-digit minute.""" hour = total_minutes // 60 minute = total_minutes % 60 return f"{DAYS[day_index]} {hour}:{minute:02d}" def merge_overlapping_intervals(intervals: List[List[str]]) -> List[List[str]]: # Phase 1: Parse strings into comparable (day_index, start_min, end_min) tuples # and sort chronologically by day (Mon..Sun), then by start time. parsed = [] for start_text, end_text in intervals: day_index, start_min = parse_time(start_text) _, end_min = parse_time(end_text) parsed.append((day_index, start_min, end_min)) parsed.sort() # Phase 2: Sweep through sorted blocks and merge overlapping same-day windows. # merged: list of mutable [day_index, start_min, end_min] blocks, e.g. [[2, 510, 825]]. merged: List[List[int]] = [] for day_index, start_min, end_min in parsed: # Use '<=' because touching endpoints (e.g. 12:30 and 12:30) count as overlapping. if merged and merged[-1][0] == day_index and start_min <= merged[-1][2]: # Take max() so a shorter window nested inside a longer one does not shrink it. merged[-1][2] = max(merged[-1][2], end_min) else: merged.append([day_index, start_min, end_min]) # Phase 3: Format each merged numeric block back into '<Day> <H>:<MM>' strings. result = [] for day_index, start_min, end_min in merged: result.append([format_time(day_index, start_min), format_time(day_index, end_min)]) return result✅ Submit now — all tests should pass.
Intuition & how it works
Imagine organizing appointment sticky notes on a seven-column weekly planner from Monday to Sunday. When the notes sit in a shuffled pile, testing every pair to see whether two blocks collide is tedious and slow. Instead, if you convert every clock string into minutes since midnight and line up each day's notes from earliest start time to latest, you can run a single sweep (a one-pass left-to-right scan over sorted items): track your active busy block, and whenever the next block on that same weekday starts before or right as the active block ends, stretch the active block's end time to cover both.
The naive approach fails for two reasons. First, sorting raw strings uses lexicographical order (character-by-character dictionary comparison), which puts "Fri" ahead of "Tue" and "10:00" ahead of "9:30" because '1' precedes '9'. Second, repeatedly scanning an unsorted list to fuse overlapping pairs one at a time takes O(n^2) to O(n^3) work, whereas sorting once lets us decide every merge in O(1) time by looking solely at the latest merged block.
Walk through [["Fri 08:15", "Fri 09:45"], ["Tue 16:00", "Tue 17:30"], ["Fri 9:30", "Fri 11:20"]]:
- Parse each block into
(day_index, start_min, end_min):(4, 495, 585),(1, 960, 1050),(4, 570, 680). - Sort the tuples:
(1, 960, 1050)comes first (Tuesday), followed by(4, 495, 585)and(4, 570, 680)(Friday). - Sweep: start
[1, 960, 1050]; start[4, 495, 585]because day4 != 1; then merge(4, 570, 680)into[4, 495, 585]because570 <= 585, extending its end tomax(585, 680) = 680. - Format back to strings:
[["Tue 16:00", "Tue 17:30"], ["Fri 8:15", "Fri 11:20"]].
Complexity
Let n be the number of input intervals.
- Time: O(n log n). Parsing
nshort strings takesO(n)time (withO(1)dictionary lookup inDAY_TO_INDEX), sorting thentuples takesO(n log n)time, and the single merge sweep plus string formatting each visit at mostnitems inO(n)time. - Space: O(n). We allocate
O(n)space for theparsedlist ofntuples, as well as up tonentries inmergedandresultwhen no intervals overlap (DAYSandDAY_TO_INDEXare fixed 7-item constants).
Edge cases
- Empty input (
[]): loops zero times and returns[]. - Single interval with leading zero (
[["Wed 08:05", "Wed 09:00"]]): still normalized byformat_timeto[["Wed 8:05", "Wed 9:00"]]. - Touching endpoints (
12:30and12:30): merged into one continuous block because the condition uses<=. - One-minute gap (
9:00-10:00and10:01-11:00):601 <= 600isFalse, so they properly stay separate. - Nested or duplicate intervals (
9:00-17:00and10:00-11:00): absorbed without shrinking17:00thanks tomax(merged[-1][2], end_min). - Adjacent days (
Mon 22:00-23:59andTue 0:00-1:00): never merged becausemerged[-1][0] == day_indexrequires the exact same day. - Out-of-order overlap chains (
14:00-15:00,9:00-10:00,11:30-14:00,10:00-12:00): sorting aligns them in start order so one pass collapses the entire chain into9:00-15:00.
Common mistakes
- Sorting raw strings instead of parsed numbers: orders days alphabetically (
Fri, Mon, Sat, Sun, Thu, Tue, Wed) and orders"10:00"before"9:30". - Using
<instead of<=for overlap: leaves[10:00, 12:30]and[12:30, 15:15]separate, failing Example 2. - Overwriting
merged[-1][2] = end_mininstead ofmax(...): shrinks a long block like9:00-17:00when a shorter block like10:00-11:00starts inside it. - Comparing only against the previous input interval instead of
merged[-1]: misses overlaps when a long early window bridges across several shorter later windows. - Reusing raw input strings in the output: returns
"Fri 08:15"instead of"Fri 8:15"when an unmerged start timestamp had a leading zero. - Forgetting
:02dwhen formatting minutes: formats8hours and5minutes as"8:5"instead of"8:05".
Alternative approaches
- Single week-minute coordinate (
day_index * 1440 + minutes): maps Monday0:00through Sunday23:59onto0..10079. Because every block ends at or before23:59(<= 1439within its day) while the next day starts at>= 1440, same-day blocks never touch across midnight unless"24:00"were allowed — keepingday_indexseparate makes the day boundary explicit and bug-proof. - Bucket sort over the 10,080 minutes of a week: bucket sort places items directly into an array indexed by their integer key instead of comparing items pairwise. Because
(day_index, start_min)has only7 * 1440 = 10,080possible slots, storing the maximumend_minseen for each slot and sweeping the 10,080 slots runs inO(n + 10,080)time, beatingO(n log n)whennis huge.
Follow-up questions
- How would your design change if intervals could cross midnight or wrap from Sunday night into Monday morning? Map every timestamp onto a single circular weekly timeline from
0(Mon 0:00) to10,080(7 * 1440). Any booking withstart < endbecomes[start, end], while a week-wrapping booking withstart > end(such asSun 22:00toMon 2:00) splits into[start, 10080]and[0, end]. Sort and merge all segments on0..10080using<=, and if the last merged block ends at10080while the first begins at0, stitch them back into[last_start, first_end]. - How could you support inserting a single new booking into an already-merged weekly calendar without re-sorting everything? Because the merged schedule is already sorted and disjoint, binary search (repeatedly halving the sorted list to locate a position in
O(log n)comparisons, such as Python'sbisect) finds the first block on that weekday ending at>= new_startand the last block starting at<= new_end. Replace that contiguous slice ofmoverlapping blocks with[day, min(new_start, first_start), max(new_end, last_end)]; using a balanced search tree (a sorted tree that maintainsO(log n)height under insertions and deletions) avoids Python list-shifting overhead and runs inO((m + 1) log n)time. - How would you find common open meeting windows of at least k minutes across several people's schedules? Concatenate everyone's busy intervals into one combined list and run
merge_overlapping_intervalsinO(N log N)time forNtotal bookings to get the union of busy blocks. Within each day's allowed working hours (for example9:00to17:00), inspect the gaps before the first block, between adjacent blocks, and after the last block, returning every gap wheregap_end - gap_start >= k.
Follow-up questions
- How would your design change if intervals could cross midnight or wrap from Sunday night into Monday morning?
- How could you support inserting a single new booking into an already-merged weekly calendar without re-sorting everything?
- How would you find common open meeting windows of at least k minutes across several people's schedules?
Similar questions
- Score-Ranked Feed with Three-Photo Grouping
- Flatten Threaded Comments
- Collapse Photo Streaks and Sort Feed
- Lexicographically Smallest Dependency Ordering
- Extended Semantic Version Comparator
- Transaction Lock Manager Simulation
More Nextdoor interview questions
- Transactional Key-Value Store with Nested Savepoints Medium
- Recruiter Screen: Motivation, ML Projects, and Recent Research Medium
- Score-Ranked Feed with Three-Photo Grouping Medium Pro
- End-to-End Tabular ML Pipeline in Pure NumPy Medium Pro
- Tabular Classification Training and Batch Scoring Pipeline Medium Pro
- CAP Trade-Offs, Distributed Architecture, and Multithreading in Practice Hard Pro
- Presenting Key ML Projects and Onboarding Logistics Medium Pro
- Analytical Data Model for KPI Dashboards, Retention, and Timezones Hard Pro
- Asynchronous Background Job Scheduler Scaling 100x Medium Pro
- Privacy-Bounded Local Community Feed and Urgent Alert System Medium Pro