Schedule Weekly Release Slots Around Freeze Windows

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Release automation follows a weekly cycle spanning 10,080 minutes (7 days × 1,440 minutes per day), where UTC minute 0 marks the start of week 0 and UTC minute 10,080 begins week 1. Engineering teams publish weekly window rules that either permit or block software releases, and you must return the upcoming continuous release slots:

def deployable_slots(utc_now: int, lead_time_minutes: int, min_continuous_minutes: int, k: int, windows: list[tuple[int, int, str, int]]) -> list[list[int]]:

Every rule in windows is a 4-tuple (start, end, kind, offset) governed by the following semantics:

  • Local half-open span: start and end specify weekly minutes on the rule's local clock covering [start, end) (inclusive of start, exclusive of end).
  • Rule kind: kind is either "allowed" (permits releases) or "freeze" (blocks releases).
  • Time-zone shift & weekly repetition: offset equals local_minute - utc_minute (for example, -300 for UTC-5 or 180 for UTC+3). Subtracting offset converts the base weekly rule to UTC [start - offset, end - offset), and weekly periodicity repeats that span at [start - offset + 10080 * m, end - offset + 10080 * m) for every integer m (..., -2, -1, 0, 1, 2, ...). Shifted copies can cross multiples of 10,080.
  • Freeze precedence: an integer UTC minute t is deployable if and only if at least one "allowed" copy contains t and zero "freeze" copies contain t.
  • One-week lookahead horizon: given the current weekly UTC minute utc_now and required preparation buffer lead_time_minutes, releases cannot begin before earliest = utc_now + lead_time_minutes. Evaluate strictly inside the 1-week window [earliest, earliest + 10080), truncating any run that extends past either endpoint of this horizon.
  • Maximal slots, minimum duration, and result cap k: merge overlapping or immediately adjacent deployable ranges inside [earliest, earliest + 10080) into maximal half-open stretches [slot_start, slot_end)—even across separate rules, distinct offsets, or week rollovers. After truncating to the horizon, keep only stretches with slot_end - slot_start >= min_continuous_minutes, and return up to k qualifying stretches as [slot_start, slot_end] pairs sorted by ascending slot_start (returning all of them if fewer than k qualify, or [] if none qualify).

Examples

Example 1

Input:
utc_now = 0, lead_time_minutes = 0, min_continuous_minutes = 1, k = 5
windows = [
  (300, 700, "allowed", 0),
  (500, 560, "freeze", 0),
  (650, 900, "allowed", 0),
  (9800, 10080, "allowed", 0),
  (0, 90, "allowed", 0)
]

Output:
[[0, 90], [300, 500], [560, 900], [9800, 10080]]

Here earliest = 0, so the lookahead horizon is [0, 10080). Overlapping allowed rules [300, 700) and [650, 900) coalesce into [300, 900), and freeze [500, 560) splits that span into [300, 500) and [560, 900). Because the horizon is clipped at 0 and 10080, [0, 90) and [9800, 10080) remain two distinct slots at opposite ends of the horizon.

Example 2

Input:
utc_now = 9950, lead_time_minutes = 50, min_continuous_minutes = 60, k = 3
windows = [
  (9900, 10080, "allowed", 0),
  (0, 180, "allowed", 0),
  (40, 80, "freeze", 0),
  (200, 240, "allowed", 0),
  (600, 750, "allowed", 180)
]

Output:
[[10000, 10120], [10160, 10260], [10500, 10650]]

earliest = 10000 sets the horizon to [10000, 20080). Week 0's [9900, 10080) is clipped at 10000 and joins seamlessly with week 1's [10080, 10260), then week 1's freeze [10120, 10160) splits it into [10000, 10120) (120 min) and [10160, 10260) (100 min). Week 1's [10280, 10320) is only 40 minutes (< 60) and is discarded. The UTC+3 rule (600, 750, "allowed", 180) maps to base UTC [420, 570), which recurs in week 1 as [10500, 10650) (150 min). Although [19980, 20080) also qualifies (100 min), k = 3 caps the output at the first three slots.

Example 3

Input:
utc_now = 80, lead_time_minutes = 20, min_continuous_minutes = 40, k = 5
windows = [
  (0, 300, "allowed", 180),
  (40, 100, "freeze", 180)
]

Output:
[[9900, 9940], [10000, 10180]]

With offset = 180, the allowed rule covers base UTC [-180, 120) and next week's [9900, 10200), while the freeze covers [-140, -80) and [9940, 10000). Inside the horizon [100, 10180), the leading remnant [100, 120) lasts 20 minutes (< 40, dropped), [9900, 9940) lasts 40 minutes (kept), and [10000, 10200) is truncated at 10180 to [10000, 10180) (180 minutes, kept).

Constraints

  • 0 <= utc_now < 10080
  • 0 <= lead_time_minutes <= 10^6
  • 1 <= min_continuous_minutes <= 10080
  • 1 <= k <= 10^4
  • 0 <= len(windows) <= 10^4
  • For each (start, end, kind, offset) in windows:
    • 0 <= start < end <= 10080
    • kind is "allowed" or "freeze"
    • -720 <= offset <= 840
  • All returned coordinates fall in [0, earliest + 10080] (<= 1,020,159).

Step-by-step walkthrough

  1. Understand the timeline and the search horizon

    Every window (start, end, type, offset) describes a weekly rule over a 10,080-minute week (7 * 24 * 60 = 10080):

    • Half-open ranges: [start, end) includes minute start and stops just before minute end, so its length is end - start minutes.
    • Time-zone conversion: offset equals local_time - utc_time. Rearranging gives utc_time = local_time - offset. For example, a UTC+3 window (offset = 180) at local [0, 300) occurs at UTC [-180, 120).
    • Weekly repetition: Each window repeats every 10,080 minutes forever in both directions: [start - offset + 10080 * m, end - offset + 10080 * m) for every integer m.
    • Freeze wins: A minute is deployable if at least one "allowed" copy covers it and zero "freeze" copies cover it.

    We cannot deploy before earliest = utc_now + lead_time_minutes, and because the schedule repeats every week, we only look inside the one-week search horizon [earliest, earliest + 10080):

    UTC timeline (minutes):
    ... |--------- Week 0 ---------|--------- Week 1 ---------| ...
        0                        10080                      20160
                  |<-------- search horizon -------->|
               earliest                     earliest + 10080
    

    Any deployable run is clipped at both ends of this horizon, kept only if its clipped length is at least min_continuous_minutes, and we return the first k slots in time order.

  2. Why minute-by-minute checking falls short

    Because the search horizon is always 10,080 minutes long, a brute-force solution could allocate two 10,080-element boolean arrays (allowed and frozen), mark each covered minute for every window, and scan for consecutive runs where allowed[t] and not frozen[t].

    That approach is great for testing (and our test suite uses it as a reference), but with up to n = 10,000 windows, marking individual minutes can perform roughly 10,080 * 10,000 ≈ 10^8 loop iterations. Worse, its speed depends on the clock resolution: switching from minutes to seconds would make it 60 times slower.

    Working directly with intervals avoids touching individual minutes. Each repeating window contributes at most two intervals to the horizon, so we can merge and subtract intervals in O(n log n) time regardless of how many minutes or seconds are in a week.

  3. Shift every window into horizon-relative coordinates

    Dealing with negative UTC times, large lead_time_minutes (up to 10^6, nearly 100 weeks), and week boundaries all at once is error-prone. All three headaches vanish if we measure time relative to earliest:

    • Relative minute 0 means absolute minute earliest.
    • Relative minute 10080 means absolute minute earliest + 10080.
    • The search horizon becomes the fixed box [0, 10080).

    Consider a window with utc_start = start - offset and duration = end - start (where 1 <= duration <= 10080). Its weekly copies start at utc_start - earliest + 10080 * m relative to earliest. Because consecutive copies are spaced by exactly 10080 minutes, exactly one copy starts inside [0, 10080):

    rel_start = (utc_start - earliest) % 10080
    rel_end   = rel_start + duration
    

    In Python, % 10080 always produces a result in 0 .. 10079, even when utc_start - earliest is negative. From there, only two shapes are possible:

    Case 1: rel_end <= 10080 (fits completely inside the horizon)
      0          rel_start      rel_end          10080
      |--------------|============|----------------|
                     one piece: [rel_start, rel_end)
    
    Case 2: rel_end > 10080 (runs past the right edge of the horizon)
      0   rel_end-10080          rel_start       10080   rel_end
      |========|---------------------|=============|........|
       tail of previous week's copy   this copy clipped at 10080
    

    In Case 2, the copy starting at rel_start gets clipped to [rel_start, 10080), and the copy from one week earlier (starting at rel_start - 10080 < 0) ends at rel_end - 10080 > 0, contributing [0, rel_end - 10080). Because duration <= 10080, no earlier or later weekly copy can reach [0, 10080).

    MINUTES_PER_WEEK = 10080  # 7 days * 24 hours * 60 minutes
    
    
    def to_horizon_pieces(
        start: int, end: int, offset: int, earliest: int
    ) -> List[List[int]]:
        """Map one weekly window into [0, MINUTES_PER_WEEK) measured relative to earliest.
    
        Returns one interval [[rel_start, rel_end]] if the weekly copy fits inside the
        horizon, or two intervals [[rel_start, MINUTES_PER_WEEK], [0, overflow]] if it
        wraps across the horizon boundary.
        """
        # offset is (local - UTC), so UTC = local - offset.
        utc_start = start - offset
        duration = end - start
    
        # Every weekly copy starts at utc_start + m * MINUTES_PER_WEEK.
        # Modulo finds the unique copy whose start lands in [earliest, earliest + 10080).
        rel_start = (utc_start - earliest) % MINUTES_PER_WEEK
        rel_end = rel_start + duration
    
        if rel_end <= MINUTES_PER_WEEK:
            return [[rel_start, rel_end]]
    
        # This copy runs past the end of the horizon, which also means the previous
        # week's copy (shifted back by 10080) is still active at relative minute 0.
        return [[rel_start, MINUTES_PER_WEEK], [0, rel_end - MINUTES_PER_WEEK]]
    
  4. Merge overlapping and touching intervals

    Consecutive deployable minutes belong to the same slot even if they come from different windows. For half-open intervals, [0, 60) covers minutes 0..59 and [60, 120) covers minutes 60..119 — there is no gap between minute 59 and minute 60!

    So after sorting intervals by start time, the next interval [start, end) joins the previous merged interval whenever start <= merged[-1][1] (using <=, not <). We apply the exact same merge function to both allowed_pieces and frozen_pieces so each list becomes sorted and completely disjoint.

    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        """Sort half-open [start, end) intervals and merge overlapping or touching ones."""
        if not intervals:
            return []
    
        sorted_intervals = sorted(intervals)
        # merged: list of disjoint, non-touching [start, end] pairs in increasing order.
        merged: List[List[int]] = [sorted_intervals[0][:]]
    
        for start, end in sorted_intervals[1:]:
            # Use <= (not <) so touching ranges like [0, 60) and [60, 120) join into
            # one continuous run [0, 120).
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                merged.append([start, end])
    
        return merged
    
  5. Cut freeze intervals out of allowed intervals

    Now we have two sorted lists of disjoint intervals: allowed and frozen. We sweep through allowed from left to right while advancing a single index freeze_idx through frozen:

    1. Any freeze with freeze_end <= allowed_start ends before this allowed interval even begins (and before all later allowed intervals), so we advance freeze_idx past it.
    2. Maintain cursor, the first minute inside [allowed_start, allowed_end) we have not yet accounted for.
    3. For each freeze with freeze_start < allowed_end:
      • If freeze_start > cursor, the uncovered stretch [cursor, freeze_start) is deployable!
      • Move cursor = max(cursor, freeze_end) to jump past the freeze.
      • If freeze_end > allowed_end, this freeze extends beyond the current allowed interval and might also overlap the next allowed interval, so we break without incrementing freeze_idx. Otherwise we increment freeze_idx.
    4. After the inner loop, if cursor < allowed_end, the remaining tail [cursor, allowed_end) is deployable.
    Allowed:     [100 ===================================== 500)
    Frozen:            [180 === 240)       [350 === 420)
    cursor walk:  100 -> emit [100,180)
                        cursor=240 ------> emit [240,350)
                                            cursor=420 ---> emit [420,500)
    

    Because every step of the inner loop either increments freeze_idx (at most len(frozen) times total) or breaks to the next allowed interval (at most len(allowed) times total), the entire subtraction pass runs in linear time.

    def subtract_intervals(
        allowed: List[List[int]], frozen: List[List[int]]
    ) -> List[List[int]]:
        """Cut merged frozen intervals out of merged allowed intervals."""
        # free_pieces: maximal [start, end] runs in [0, 10080] that are allowed and not frozen.
        free_pieces: List[List[int]] = []
        freeze_idx = 0
    
        for allowed_start, allowed_end in allowed:
            # Skip freeze intervals that end at or before allowed_start.
            # Because intervals are half-open, a freeze ending at allowed_start shares no minutes.
            while freeze_idx < len(frozen) and frozen[freeze_idx][1] <= allowed_start:
                freeze_idx += 1
    
            # cursor tracks the first minute inside [allowed_start, allowed_end) not yet handled.
            cursor = allowed_start
            while freeze_idx < len(frozen) and frozen[freeze_idx][0] < allowed_end:
                freeze_start, freeze_end = frozen[freeze_idx]
                # Any uncovered gap before freeze_start is a deployable run.
                if freeze_start > cursor:
                    free_pieces.append([cursor, freeze_start])
                cursor = max(cursor, freeze_end)
    
                # If this freeze extends past allowed_end, keep freeze_idx pointing at it
                # because it may also cover part of the next allowed interval.
                if freeze_end > allowed_end:
                    break
                freeze_idx += 1
    
            # Any tail left after the last overlapping freeze is also deployable.
            if cursor < allowed_end:
                free_pieces.append([cursor, allowed_end])
    
        return free_pieces
    
  6. Filter by minimum duration, cap at k, and trace Example 3

    free_pieces is already maximal, non-overlapping, clipped to [0, 10080], and sorted by start time. All that remains is keeping pieces with rel_end - rel_start >= min_continuous_minutes, shifting back to absolute UTC time by adding earliest, and stopping once we have k slots.

    Let's trace Example 3: utc_now = 80, lead_time_minutes = 20, min_continuous_minutes = 40, k = 5, with windows (0, 300, "allowed", 180) and (40, 100, "freeze", 180):

    earliest = 80 + 20 = 100   (horizon is UTC [100, 10180))
    
    1. Allowed (0, 300, offset 180):
       utc_start = 0 - 180 = -180, duration = 300
       rel_start = (-180 - 100) % 10080 = 9800
       rel_end   = 9800 + 300 = 10100 > 10080
       -> wraps into [[9800, 10080], [0, 20]]
    
    2. Freeze (40, 100, offset 180):
       utc_start = 40 - 180 = -140, duration = 60
       rel_start = (-140 - 100) % 10080 = 9840
       rel_end   = 9840 + 60 = 9900 <= 10080
       -> fits as [[9840, 9900]]
    
    3. Merge & subtract:
       merged_allowed = [[0, 20], [9800, 10080]]
       merged_frozen  = [[9840, 9900]]
       free_pieces    = [[0, 20], [9800, 9840], [9900, 10080]]
    
    4. Filter (length >= 40) & add earliest (+100):
       [0, 20]       -> length 20  (< 40, dropped)
       [9800, 9840]  -> length 40  -> [9900, 9940]
       [9900, 10080] -> length 180 -> [10000, 10180]
    

    The output is [[9900, 9940], [10000, 10180]], matching Example 3.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    MINUTES_PER_WEEK = 10080  # 7 days * 24 hours * 60 minutes
    
    
    def to_horizon_pieces(
        start: int, end: int, offset: int, earliest: int
    ) -> List[List[int]]:
        """Map one weekly window into [0, MINUTES_PER_WEEK) measured relative to earliest.
    
        Returns one interval [[rel_start, rel_end]] if the weekly copy fits inside the
        horizon, or two intervals [[rel_start, MINUTES_PER_WEEK], [0, overflow]] if it
        wraps across the horizon boundary.
        """
        # offset is (local - UTC), so UTC = local - offset.
        utc_start = start - offset
        duration = end - start
    
        # Every weekly copy starts at utc_start + m * MINUTES_PER_WEEK.
        # Modulo finds the unique copy whose start lands in [earliest, earliest + 10080).
        rel_start = (utc_start - earliest) % MINUTES_PER_WEEK
        rel_end = rel_start + duration
    
        if rel_end <= MINUTES_PER_WEEK:
            return [[rel_start, rel_end]]
    
        # This copy runs past the end of the horizon, which also means the previous
        # week's copy (shifted back by 10080) is still active at relative minute 0.
        return [[rel_start, MINUTES_PER_WEEK], [0, rel_end - MINUTES_PER_WEEK]]
    
    
    def merge_intervals(intervals: List[List[int]]) -> List[List[int]]:
        """Sort half-open [start, end) intervals and merge overlapping or touching ones."""
        if not intervals:
            return []
    
        sorted_intervals = sorted(intervals)
        # merged: list of disjoint, non-touching [start, end] pairs in increasing order.
        merged: List[List[int]] = [sorted_intervals[0][:]]
    
        for start, end in sorted_intervals[1:]:
            # Use <= (not <) so touching ranges like [0, 60) and [60, 120) join into
            # one continuous run [0, 120).
            if start <= merged[-1][1]:
                merged[-1][1] = max(merged[-1][1], end)
            else:
                merged.append([start, end])
    
        return merged
    
    
    def subtract_intervals(
        allowed: List[List[int]], frozen: List[List[int]]
    ) -> List[List[int]]:
        """Cut merged frozen intervals out of merged allowed intervals."""
        # free_pieces: maximal [start, end] runs in [0, 10080] that are allowed and not frozen.
        free_pieces: List[List[int]] = []
        freeze_idx = 0
    
        for allowed_start, allowed_end in allowed:
            # Skip freeze intervals that end at or before allowed_start.
            # Because intervals are half-open, a freeze ending at allowed_start shares no minutes.
            while freeze_idx < len(frozen) and frozen[freeze_idx][1] <= allowed_start:
                freeze_idx += 1
    
            # cursor tracks the first minute inside [allowed_start, allowed_end) not yet handled.
            cursor = allowed_start
            while freeze_idx < len(frozen) and frozen[freeze_idx][0] < allowed_end:
                freeze_start, freeze_end = frozen[freeze_idx]
                # Any uncovered gap before freeze_start is a deployable run.
                if freeze_start > cursor:
                    free_pieces.append([cursor, freeze_start])
                cursor = max(cursor, freeze_end)
    
                # If this freeze extends past allowed_end, keep freeze_idx pointing at it
                # because it may also cover part of the next allowed interval.
                if freeze_end > allowed_end:
                    break
                freeze_idx += 1
    
            # Any tail left after the last overlapping freeze is also deployable.
            if cursor < allowed_end:
                free_pieces.append([cursor, allowed_end])
    
        return free_pieces
    
    
    def deployable_slots(
        utc_now: int,
        lead_time_minutes: int,
        min_continuous_minutes: int,
        k: int,
        windows: list[tuple[int, int, str, int]],
    ) -> list[list[int]]:
        # Phase 1: Express every repeating window inside the 1-week horizon [earliest, earliest + 10080)
        # using relative coordinates [0, 10080).
        earliest = utc_now + lead_time_minutes
        allowed_pieces: List[List[int]] = []
        frozen_pieces: List[List[int]] = []
    
        for start, end, window_type, offset in windows:
            pieces = to_horizon_pieces(start, end, offset, earliest)
            if window_type == "allowed":
                allowed_pieces.extend(pieces)
            else:
                frozen_pieces.extend(pieces)
    
        # Phase 2: Merge each group into clean non-overlapping ranges, then subtract freezes.
        merged_allowed = merge_intervals(allowed_pieces)
        merged_frozen = merge_intervals(frozen_pieces)
        free_pieces = subtract_intervals(merged_allowed, merged_frozen)
    
        # Phase 3: Filter by minimum continuous duration (after horizon clipping),
        # shift back to absolute UTC minutes, and cap at k slots.
        slots: List[List[int]] = []
        for rel_start, rel_end in free_pieces:
            if len(slots) == k:
                break
            if rel_end - rel_start >= min_continuous_minutes:
                slots.append([earliest + rel_start, earliest + rel_end])
    
        return slots
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture unrolling one week of a calendar onto a strip of paper starting at the first usable minute earliest = utc_now + lead_time_minutes. Each allowed window lays down a strip of green tape on that week, and each freeze window lays down a strip of red blackout tape on top of it. Any uninterrupted stretch of visible green tape that is at least min_continuous_minutes long is a deployable slot.

The obvious brute-force approach checks every one of the 10,080 minutes in the horizon against every window to see whether that minute is allowed and not frozen. With up to 10,000 windows, that takes roughly 10,080 * 10,000 ≈ 10^8 checks, which is slow in Python and would become 60 times slower if the clock used seconds instead of minutes. Worse, handling negative UTC offsets and multi-week lead times directly on absolute timestamps makes wrap-around logic messy.

Instead, we shift the origin to earliest so the horizon is always [0, 10080). Using modulo arithmetic (taking the remainder after division by 10,080 so repeating weekly times wrap cleanly into [0, 10080)), each half-open interval [start, end) (an interval that includes start and excludes end) maps to one piece inside [0, 10080), or two pieces if it crosses 10080. We then do interval merging (sorting ranges and combining any that overlap or touch) on allowed and freeze lists separately, and run a two-pointer sweep (walking through both sorted lists together in one left-to-right pass) to cut out frozen stretches.

Here is a tiny trace with a 100-minute horizon starting at earliest = 50 (instead of 10,080, to see the numbers easily):

  1. Suppose an allowed window covers [40, 90) and a freeze covers [60, 70).
  2. Relative to earliest = 50 on a 100-minute cycle, [40, 90) starts at (40 - 50) % 100 = 90 with length 50, wrapping into [90, 100) and [0, 40). The freeze [60, 70) maps to [10, 20).
  3. Cutting freeze [10, 20) out of allowed [0, 40) leaves [0, 10) and [20, 40), while [90, 100) is untouched.
  4. Adding earliest = 50 back gives absolute slots [50, 60], [70, 90], and [140, 150].

Complexity

Let n be the number of windows in windows.

  • Time: O(n log n). Converting each of the n windows into at most two horizon-relative pieces takes O(1) arithmetic per window, creating at most 2n allowed pieces and 2n freeze pieces. Sorting those pieces for merging takes O(n log n) time. Merging each sorted list scans it once in O(n) time, the two-pointer subtraction advances past each allowed and freeze piece once in O(n) time, and filtering the final pieces takes O(n) time. Notice that the runtime depends only on n, never on 10,080 or lead_time_minutes.
  • Space: O(n). We store at most 2n relative pieces across the allowed and frozen lists, plus at most O(n) merged and subtracted intervals in the output.

Edge cases

  • No windows, or only freeze windows: allowed_pieces is empty, so the function returns [].
  • Identical allowed and freeze range: freeze wins completely and removes the entire range, leaving [].
  • Touching allowed windows ([0, 60) and [60, 120)), even from different time zones: merged into [0, 120) because start <= merged[-1][1] joins adjacent half-open ranges.
  • Touching freeze window ([50, 100) against allowed [100, 300)): removes zero minutes because half-open [50, 100) ends at minute 99 while [100, 300) starts at minute 100.
  • A window straddling earliest: [50, 200) with earliest = 100 wraps into [0, 100) (tail of this week's copy) and [10030, 10080) (head of next week's copy), appearing as two separate clipped slots [100, 200] and [10130, 10180].
  • Full-week window (0, 10080): regardless of offset, its one or two pieces merge to [0, 10080), yielding [earliest, earliest + 10080] when unfrozen.
  • Offsets pushing local times below 0 or past 10080: (utc_start - earliest) % 10080 wraps both negative and >10,080 UTC starts into [0, 10080).
  • Large lead_time_minutes (up to 10^6): modulo handles the 99-week jump in O(1) while + earliest preserves the exact absolute minute in the output.
  • Exact min_continuous_minutes boundary: rel_end - rel_start >= min_continuous_minutes keeps slots whose clipped length equals the minimum and drops slots one minute shorter.

Common mistakes

  • Merging with < instead of <=: writing start < merged[-1][1] fails to merge touching allowed windows like [0, 60) and [60, 120), splitting one continuous slot in two.
  • Reversing the offset sign: since offset = local - UTC, converting to UTC requires subtracting offset (start - offset), not adding it.
  • Only checking the current week's copy ([0, 10080)): a horizon starting at utc_now = 50 reaches 10130 in the next week, and an offset window can also wrap from the previous week.
  • Splitting runs at the week boundary (10080): consecutive deployable minutes across 10080 form a single slot unless 10080 happens to be an endpoint of the search horizon.
  • Filtering by min_continuous_minutes too early: length must be checked after clipping at both ends of the horizon and after subtracting freeze windows.
  • Capping to k before filtering: k limits the number of qualifying slots, not the number of raw intervals before checking minimum length.
  • Negative modulo in other languages: Python's % always returns [0, 10080), whereas C++, Java, and JavaScript need ((x % W) + W) % W.

Alternative approaches

  • Minute-level difference array: A difference array records only +1 at each interval start and -1 at each interval end in an array of size 10081, and then takes a prefix sum (a running total from left to right) to recover how many allowed and freeze windows cover each minute. It runs in O(n + 10080) time and needs almost no casework, though its memory and runtime grow linearly if time resolution increases to seconds (604,800 cells).
  • Single event-line sweep: Turn every relative piece [s, e) into two events (s, +1, kind) and (e, -1, kind), sort all events by timestamp, and track active allowed_count and freeze_count between consecutive timestamps. Consecutive segments with allowed_count > 0 and freeze_count == 0 coalesce into slots in O(n log n) time.

Follow-up questions

  • What if the window schedule rarely changes, yet the service receives thousands of queries per second with varying current times and lead times? Precompute the merged and subtracted free intervals once on the base week [0, 10080) in O(n log n) time; if a free interval ends at 10080 and another starts at 0, note that they connect across the week boundary. On each query, compute r = earliest % 10080, use binary search (O(log P) for P free intervals) to find the first interval ending after r, clip it at r, and walk around the circular list collecting slots of length >= min_continuous_minutes up to k before clipping at r + 10080. Each query drops from O(n log n) sorting work to O(log P + visited_pieces).
  • How would daylight saving time transitions affect this weekly model, and how would you adapt the scheduler? With DST, a region's UTC offset changes twice a year, so the schedule is no longer strictly 10,080-minute periodic in UTC. Instead of a fixed integer offset, store an IANA time-zone name (such as "America/New_York"), take the real calendar dates overlapping [earliest, earliest + 10080), convert each local window occurrence on those dates to UTC using a time-zone database (handling skipped "spring forward" and repeated "fall back" hours explicitly), and run the exact same merge-and-subtract pipeline on the resulting UTC intervals.
  • What changes if every engineering team defines its own schedule and a release requires simultaneous approval from all teams? "Every team allows it" means taking the intersection of each team's merged allowed intervals rather than their union. Equivalently, by De Morgan's law, any minute outside a team's allowed windows is effectively frozen for that team: complement each team's merged allowed windows on [0, 10080) into implicit freeze intervals, combine them with all explicit freeze intervals, and subtract from [0, 10080).

Follow-up questions

Similar questions

More Stripe interview questions

All 139 Stripe questions →