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:
startandendspecify weekly minutes on the rule's local clock covering[start, end)(inclusive ofstart, exclusive ofend). - Rule kind:
kindis either"allowed"(permits releases) or"freeze"(blocks releases). - Time-zone shift & weekly repetition:
offsetequalslocal_minute - utc_minute(for example,-300for UTC-5 or180for UTC+3). Subtractingoffsetconverts 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 integerm(..., -2, -1, 0, 1, 2, ...). Shifted copies can cross multiples of10,080. - Freeze precedence: an integer UTC minute
tis deployable if and only if at least one"allowed"copy containstand zero"freeze"copies containt. - One-week lookahead horizon: given the current weekly UTC minute
utc_nowand required preparation bufferlead_time_minutes, releases cannot begin beforeearliest = 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 withslot_end - slot_start >= min_continuous_minutes, and return up tokqualifying stretches as[slot_start, slot_end]pairs sorted by ascendingslot_start(returning all of them if fewer thankqualify, 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 < 100800 <= lead_time_minutes <= 10^61 <= min_continuous_minutes <= 100801 <= k <= 10^40 <= len(windows) <= 10^4- For each
(start, end, kind, offset)inwindows:0 <= start < end <= 10080kindis"allowed"or"freeze"-720 <= offset <= 840
- All returned coordinates fall in
[0, earliest + 10080](<= 1,020,159).
Step-by-step walkthrough
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 minutestartand stops just before minuteend, so its length isend - startminutes. - Time-zone conversion:
offsetequalslocal_time - utc_time. Rearranging givesutc_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 integerm. - 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 + 10080Any 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 firstkslots in time order.- Half-open ranges:
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 (
allowedandfrozen), mark each covered minute for every window, and scan for consecutive runs whereallowed[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,000windows, marking individual minutes can perform roughly10,080 * 10,000 ≈ 10^8loop 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.Shift every window into horizon-relative coordinates
Dealing with negative UTC times, large
lead_time_minutes(up to10^6, nearly 100 weeks), and week boundaries all at once is error-prone. All three headaches vanish if we measure time relative toearliest:- Relative minute
0means absolute minuteearliest. - Relative minute
10080means absolute minuteearliest + 10080. - The search horizon becomes the fixed box
[0, 10080).
Consider a window with
utc_start = start - offsetandduration = end - start(where1 <= duration <= 10080). Its weekly copies start atutc_start - earliest + 10080 * mrelative toearliest. Because consecutive copies are spaced by exactly10080minutes, exactly one copy starts inside[0, 10080):rel_start = (utc_start - earliest) % 10080 rel_end = rel_start + durationIn Python,
% 10080always produces a result in0 .. 10079, even whenutc_start - earliestis 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 10080In Case 2, the copy starting at
rel_startgets clipped to[rel_start, 10080), and the copy from one week earlier (starting atrel_start - 10080 < 0) ends atrel_end - 10080 > 0, contributing[0, rel_end - 10080). Becauseduration <= 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]]- Relative minute
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 minutes0..59and[60, 120)covers minutes60..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 wheneverstart <= merged[-1][1](using<=, not<). We apply the exact same merge function to bothallowed_piecesandfrozen_piecesso 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 mergedCut freeze intervals out of allowed intervals
Now we have two sorted lists of disjoint intervals:
allowedandfrozen. We sweep throughallowedfrom left to right while advancing a single indexfreeze_idxthroughfrozen:- Any freeze with
freeze_end <= allowed_startends before this allowed interval even begins (and before all later allowed intervals), so we advancefreeze_idxpast it. - Maintain
cursor, the first minute inside[allowed_start, allowed_end)we have not yet accounted for. - 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 webreakwithout incrementingfreeze_idx. Otherwise we incrementfreeze_idx.
- If
- 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 mostlen(frozen)times total) orbreaks to the next allowed interval (at mostlen(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- Any freeze with
Filter by minimum duration, cap at k, and trace Example 3
free_piecesis already maximal, non-overlapping, clipped to[0, 10080], and sorted by start time. All that remains is keeping pieces withrel_end - rel_start >= min_continuous_minutes, shifting back to absolute UTC time by addingearliest, and stopping once we havekslots.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.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):
- Suppose an allowed window covers
[40, 90)and a freeze covers[60, 70). - Relative to
earliest = 50on a 100-minute cycle,[40, 90)starts at(40 - 50) % 100 = 90with length50, wrapping into[90, 100)and[0, 40). The freeze[60, 70)maps to[10, 20). - Cutting freeze
[10, 20)out of allowed[0, 40)leaves[0, 10)and[20, 40), while[90, 100)is untouched. - Adding
earliest = 50back 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
nwindows into at most two horizon-relative pieces takesO(1)arithmetic per window, creating at most2nallowed pieces and2nfreeze pieces. Sorting those pieces for merging takesO(n log n)time. Merging each sorted list scans it once inO(n)time, the two-pointer subtraction advances past each allowed and freeze piece once inO(n)time, and filtering the final pieces takesO(n)time. Notice that the runtime depends only onn, never on10,080orlead_time_minutes. - Space: O(n). We store at most
2nrelative pieces across the allowed and frozen lists, plus at mostO(n)merged and subtracted intervals in the output.
Edge cases
- No windows, or only freeze windows:
allowed_piecesis 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)becausestart <= 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)withearliest = 100wraps 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 ofoffset, its one or two pieces merge to[0, 10080), yielding[earliest, earliest + 10080]when unfrozen. - Offsets pushing local times below
0or past10080:(utc_start - earliest) % 10080wraps both negative and >10,080 UTC starts into[0, 10080). - Large
lead_time_minutes(up to10^6): modulo handles the 99-week jump inO(1)while+ earliestpreserves the exact absolute minute in the output. - Exact
min_continuous_minutesboundary:rel_end - rel_start >= min_continuous_minuteskeeps slots whose clipped length equals the minimum and drops slots one minute shorter.
Common mistakes
- Merging with
<instead of<=: writingstart < 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 subtractingoffset(start - offset), not adding it. - Only checking the current week's copy (
[0, 10080)): a horizon starting atutc_now = 50reaches10130in the next week, and an offset window can also wrap from the previous week. - Splitting runs at the week boundary (
10080): consecutive deployable minutes across10080form a single slot unless10080happens to be an endpoint of the search horizon. - Filtering by
min_continuous_minutestoo early: length must be checked after clipping at both ends of the horizon and after subtracting freeze windows. - Capping to
kbefore filtering:klimits 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
+1at each interval start and-1at each interval end in an array of size10081, 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 inO(n + 10080)time and needs almost no casework, though its memory and runtime grow linearly if time resolution increases to seconds (604,800cells). - 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 activeallowed_countandfreeze_countbetween consecutive timestamps. Consecutive segments withallowed_count > 0andfreeze_count == 0coalesce into slots inO(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)inO(n log n)time; if a free interval ends at10080and another starts at0, note that they connect across the week boundary. On each query, computer = earliest % 10080, use binary search (O(log P)forPfree intervals) to find the first interval ending afterr, clip it atr, and walk around the circular list collecting slots of length>= min_continuous_minutesup tokbefore clipping atr + 10080. Each query drops fromO(n log n)sorting work toO(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
- What if the window schedule rarely changes, yet the service receives thousands of queries per second with varying current times and lead times?
- How would daylight saving time transitions affect this weekly model, and how would you adapt the scheduler?
- What changes if every engineering team defines its own schedule and a release requires simultaneous approval from all teams?
Similar questions
- Pull Request Reviewer Selection via File Ownership
- Task Scheduling with Worker Account Affinity
- Credit-Backed Account Transfer Ledger
- Monthly Invoice Calculator with Tiered Usage
- Merchant Payment Fee Engine for CSV Logs
- Multi-Currency Ledger with Overdraft Coverage
More Stripe interview questions
- Event-Driven Subscription Notification Scheduler Medium
- Split-Tender Checkout Processor with Expiring Gift Cards Hard
- Rewinding Stream Request Bodies Across HTTP 307/308 Redirects Medium Pro
- Connected User Profiles via Weighted Similarity Medium Pro
- Three-Tier Payment-to-Invoice Reconciliation Medium Pro
- Reconcile Payments Against Invoices Easy Pro
- Post Moderation Policy Engine With Chained Boolean Rules Hard Pro
- Left-to-Right Payment Rule Evaluator with Grouped Conditions Hard Pro
- Spherical Distance and Healthy Region Routing Medium Pro
- Priority-Based Invoice Payment Reconciliation Medium Pro