Weekly Deploy Windows with Time Zones and Blackouts
Greedy & IntervalsAuto-graded · 20 test casesLast updated
Convert weekly recurring allow and freeze windows from local time zones to UTC, subtract the freezes, and list the first usable slots after a notice period.
Weekly Deploy Windows
A platform team schedules database maintenance on a calendar that repeats every week. Time is counted in whole minutes, and one full cycle has W = 10080 minutes (7 * 24 * 60).
Regional teams each publish rules. A rule has one of two kinds:
"open": maintenance is allowed during the rule's window."blackout": maintenance is forbidden during the rule's window. A blackout always overrides any number of open rules.
A minute is usable if at least one open rule covers it and no blackout rule covers it. A slot is a maximal run of consecutive usable minutes, written as a half-open interval [start, end). Two windows that merely touch, such as [a, b) and [b, c), form one continuous run.
Rule format
Each rule is (start, end, kind, utc_offset):
startandendare minutes in the rule's local week, with0 <= start < end <= W.utc_offsetis local time minus UTC, in minutes (UTC+2 is120, UTC-1 is-60).- In UTC, the rule covers
[start - utc_offset, end - utc_offset). - The rule repeats every
Wminutes in both directions, so a converted window may start before minute 0 or extend past minuteW. Those parts belong to the neighbouring weeks.
Task
Implement plan_windows(now_minute, notice, min_length, limit, rules).
now_minuteis the current minute within the current UTC week (0 <= now_minute < W).- Maintenance cannot begin before
lo = now_minute + notice. - Only the horizon
[lo, lo + W)is considered. Slots that cross either edge of the horizon are clipped to it. - Discard slots whose length (
end - start) is less thanmin_length. - Return the first
limitremaining slots in increasing time order, each as[start, end]. - Times are on one continuous UTC timeline, so minute
Wis the start of the next week and returned values may exceedW.
If no slot qualifies, return an empty list.
Constraints
1 <= len(rules) <= 10^40 <= now_minute < 100800 <= notice <= 10^5|utc_offset| <= 14400 <= start < end <= 10080for every rulekindis either"open"or"blackout"min_length >= 1,limit >= 1
Examples
Example 1
Input: plan_windows(0, 0, 1, 99, [[540, 1020, 'open', 0], [1980, 2460, 'open', 0], [600, 660, 'blackout', 0], [2400, 2520, 'blackout', 0]])
Output: [[540, 600], [660, 1020], [1980, 2400]]
Example 2
Input: plan_windows(0, 0, 1, 99, [[9900, 10080, 'open', 0], [0, 120, 'open', 0], [480, 600, 'open', 120], [10020, 10080, 'blackout', -60]])
Output: [[60, 120], [360, 480], [9900, 10080]]
Example 3
Input: plan_windows(9950, 30, 45, 2, [[9900, 10080, 'open', 0], [0, 120, 'open', 0], [480, 600, 'open', 120], [10020, 10080, 'blackout', -60]])
Output: [[9980, 10080], [10140, 10200]]
Hints
Hint 1
First convert every rule to UTC and fix the horizon [lo, lo + W). Because each rule is at most W long, only a couple of weekly copies of it can touch the horizon. Floor division gives the first relevant copy, even for negative shifts.
Hint 2
Clip each weekly copy to the horizon and drop empty pieces. Then you only have plain intervals on a line, each labelled open or blackout.
Hint 3
Sweep over the sorted endpoints while tracking how many open and how many blackout intervals are active. A stretch is usable when open > 0 and blackout == 0. Extend the previous slot if it ends exactly where the new stretch starts, then filter by min_length and cut to limit.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
- Horizon. Let
lo = now_minute + noticeandhi = lo + W. Because the schedule repeats weekly, a window of lengthWshows every distinct situation. - Expand rules into UTC. A rule covers
[start - offset, end - offset)in UTC, shifted by any multiple ofW. For each shiftkfrom(lo - end_utc) // Wto(hi - start_utc) // W, build the copy, clip it to[lo, hi), and skip it if it is empty. Python's floor division handles negative values correctly. Since a rule is at mostWlong, only about two copies actually survive the clipping. - Sweep line. For each surviving copy, record at its left endpoint
+1to the open or blackout counter, and at its right endpoint-1. Sort all distinct endpoints and walk through them while maintaining the two counters. - Extract slots. Between two consecutive endpoints, every minute has the same counters. That stretch is usable exactly when
open > 0andblackout == 0. If the previous slot ends exactly where this stretch begins, extend it so that slots stay maximal. Otherwise start a new slot. - Filter and cap. Keep slots with
end - start >= min_lengthand return the firstlimit.
Why it is correct
Counters only change at endpoints, so the usable status is constant between neighbouring endpoints and checking each gap covers every minute. Merging stretches that touch gives maximal runs. Half-open intervals mean a blackout ending at b leaves minute b usable, and touching opens join naturally. Clipping to the horizon implements the rule that slots are reported only within [lo, hi).
Complexity
With n rules there are at most about 2n clipped copies, so O(n) events. Sorting them dominates: O(n log n) time and O(n) space.
Reference solution
from typing import List, Tuple
W = 10080
def plan_windows(now_minute: int, notice: int, min_length: int, limit: int,
rules: List[Tuple[int, int, str, int]]) -> List[List[int]]:
lo = now_minute + notice
hi = lo + W
# events[t] = [change in active open count, change in active blackout count]
events = {}
for start, end, kind, utc_offset in rules:
base_start = start - utc_offset
base_end = end - utc_offset
is_open = kind == "open"
# Candidate weekly copies; keep only those intersecting the horizon.
first_k = (lo - base_end) // W
last_k = (hi - base_start) // W
for k in range(first_k, last_k + 1):
left = max(lo, base_start + k * W)
right = min(hi, base_end + k * W)
if left >= right:
continue
start_delta = (1, 0) if is_open else (0, 1)
end_delta = (-start_delta[0], -start_delta[1])
for point, delta in ((left, start_delta), (right, end_delta)):
if point not in events:
events[point] = [0, 0]
events[point][0] += delta[0]
events[point][1] += delta[1]
points = sorted(events)
open_count = blackout_count = 0
slots = []
for i, point in enumerate(points[:-1]):
open_delta, blackout_delta = events[point]
open_count += open_delta
blackout_count += blackout_delta
next_point = points[i + 1]
if open_count > 0 and blackout_count == 0 and point < next_point:
if slots and slots[-1][1] == point:
slots[-1][1] = next_point
else:
slots.append([point, next_point])
return [slot for slot in slots if slot[1] - slot[0] >= min_length][:limit]