Merge Overlapping Incident Intervals for Downtime
Problem Statement
Compute total downtime from a set of alert intervals that may overlap or be reported by multiple monitors. Overlapping intervals count once.
Background
Given a list of (start, end) outage intervals, merge overlapping/adjacent ones and sum their lengths. Two intervals overlap if one starts at or before the other ends. The total downtime is the sum of merged interval lengths.
Your Task
def total_downtime(intervals):
Return the total covered duration (number).
Input Format
- intervals (list of (start, end) numeric tuples, start <= end).
Output Format
- A number (total downtime).
Sample
print(total_downtime([(0, 10), (5, 15), (20, 25)]))
Output:
20
Example
print(total_downtime([(0, 10), (5, 15), (20, 25)]))
20
- Sort the input intervals by their start times to process them in chronological order: .
- Initialize the current merged interval with the first pair, setting the current start to and current end to .
- Process the next interval : since its start () is less than or equal to the current end (), the intervals overlap; update the current end to the maximum of and , resulting in a merged interval of .
- Process the final interval : since its start () is greater than the current end (), there is no overlap; add the length of the previous merged interval () to the total and start a new current interval .
- Add the length of the last remaining interval to the total: .
- The final output is 20
Constraints
- Merge intervals that overlap or touch (
next.start <= cur.end). - Sum merged lengths.
- Empty list -> 0.