Skip to content
Coding · Easy · Intervals · Target O(n log n) · Mid

Merge maintenance windows

Merge each service's overlapping or touching maintenance windows and report its total scheduled downtime, with unsorted, nested and zero-length windows in the input.

Statement

A change calendar holds planned maintenance as (service, start, end), with start and end in whole minutes since the start of the week and start ≤ end. Teams file windows independently, so one service's windows can overlap, repeat, sit inside one another or meet end to start.

Write scheduled_downtime(windows). For each service, merge the windows that overlap or touch into one and return {service: {"windows": [(start, end), ...], "total": minutes}}, with the merged windows sorted by start and total the sum of their lengths. Windows of different services never merge.

Examples

Two services, filed in no particular order

windows = [("api", 0, 30), ("db", 10, 20), ("api", 20, 45),
           ("api", 60, 90), ("db", 18, 25)]

→ {"api": {"windows": [(0, 45), (60, 90)], "total": 75},
   "db":  {"windows": [(10, 25)], "total": 15}}

Constraints

Up to 10⁵ windows in any order. Windows that touch (end == next start) merge. A zero-length window (start == end) is no downtime and is never reported as a window, but its service still appears in the result, with an empty list and a total of 0 if it has nothing else. No windows at all returns {}.

Free to try · sign in to save your attemptSolve it in the editor with visible tests
Open in the app