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, or Sun).
  • Every timestamp represents a valid 24-hour clock time from 0:00 through 23:59, with start_time strictly before end_time.
  • Your algorithm should run faster than O(n^2) time on large inputs.

Step-by-step walkthrough

  1. 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 of Mon, 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 Mon through Sun, 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).
  2. 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 to O(n^3) across n - 1 merges), which is far too slow when n reaches 10^5.

  3. Turn strings into `(day_index, minutes_since_midnight)`

    Mapping Mon..Sun to 0..6 and converting H:MM into H * 60 + MM minutes 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 = 680
    

    int("08") and int("8") both evaluate to 8, 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 :02d so 5 minutes 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}"
    
  4. 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 by day_index (0..6), then by start_min, then by end_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 block
    

    Why 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!

  5. Code the sort, merge sweep, and formatting

    Watch two subtle details in the sweep:

    1. Check start_min <= merged[-1][2] with <= (not <) so touching endpoints combine.
    2. 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
    
  6. 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"]]
    
  7. 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"]]:

  1. Parse each block into (day_index, start_min, end_min): (4, 495, 585), (1, 960, 1050), (4, 570, 680).
  2. Sort the tuples: (1, 960, 1050) comes first (Tuesday), followed by (4, 495, 585) and (4, 570, 680) (Friday).
  3. Sweep: start [1, 960, 1050]; start [4, 495, 585] because day 4 != 1; then merge (4, 570, 680) into [4, 495, 585] because 570 <= 585, extending its end to max(585, 680) = 680.
  4. 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 n short strings takes O(n) time (with O(1) dictionary lookup in DAY_TO_INDEX), sorting the n tuples takes O(n log n) time, and the single merge sweep plus string formatting each visit at most n items in O(n) time.
  • Space: O(n). We allocate O(n) space for the parsed list of n tuples, as well as up to n entries in merged and result when no intervals overlap (DAYS and DAY_TO_INDEX are 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 by format_time to [["Wed 8:05", "Wed 9:00"]].
  • Touching endpoints (12:30 and 12:30): merged into one continuous block because the condition uses <=.
  • One-minute gap (9:00-10:00 and 10:01-11:00): 601 <= 600 is False, so they properly stay separate.
  • Nested or duplicate intervals (9:00-17:00 and 10:00-11:00): absorbed without shrinking 17:00 thanks to max(merged[-1][2], end_min).
  • Adjacent days (Mon 22:00-23:59 and Tue 0:00-1:00): never merged because merged[-1][0] == day_index requires 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 into 9: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_min instead of max(...): shrinks a long block like 9:00-17:00 when a shorter block like 10:00-11:00 starts 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 :02d when formatting minutes: formats 8 hours and 5 minutes as "8:5" instead of "8:05".

Alternative approaches

  • Single week-minute coordinate (day_index * 1440 + minutes): maps Monday 0:00 through Sunday 23:59 onto 0..10079. Because every block ends at or before 23:59 (<= 1439 within its day) while the next day starts at >= 1440, same-day blocks never touch across midnight unless "24:00" were allowed — keeping day_index separate 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 only 7 * 1440 = 10,080 possible slots, storing the maximum end_min seen for each slot and sweeping the 10,080 slots runs in O(n + 10,080) time, beating O(n log n) when n is 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) to 10,080 (7 * 1440). Any booking with start < end becomes [start, end], while a week-wrapping booking with start > end (such as Sun 22:00 to Mon 2:00) splits into [start, 10080] and [0, end]. Sort and merge all segments on 0..10080 using <=, and if the last merged block ends at 10080 while the first begins at 0, 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's bisect) finds the first block on that weekday ending at >= new_start and the last block starting at <= new_end. Replace that contiguous slice of m overlapping blocks with [day, min(new_start, first_start), max(new_end, last_end)]; using a balanced search tree (a sorted tree that maintains O(log n) height under insertions and deletions) avoids Python list-shifting overhead and runs in O((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_intervals in O(N log N) time for N total bookings to get the union of busy blocks. Within each day's allowed working hours (for example 9:00 to 17:00), inspect the gaps before the first block, between adjacent blocks, and after the last block, returning every gap where gap_end - gap_start >= k.

Follow-up questions

Similar questions

More Nextdoor interview questions

All 21 Nextdoor questions →