Skip to content
Coding · Medium · Intervals · Target O(n log n + m·n) · Senior

Availability from incident intervals

Turn a list of incident intervals into an availability percentage for each UTC calendar month, counting overlapping incidents once and splitting downtime at month boundaries.

Statement

Incidents are (start, end) Unix timestamps in seconds, half-open: the service is down from start up to but not including end. They may overlap, sit inside one another, arrive in any order and run across month boundaries. Write monthly_availability(incidents, months) that returns, for each (year, month) in months, the percentage of that UTC calendar month during which no incident was open.

Time covered by several incidents counts once. Only the part of an incident that falls inside a month counts against that month. An incident whose end is not after its start counts for nothing.

Return a dict keyed by (year, month). Each value is the float 100 × (seconds in the month − seconds down) ÷ seconds in the month, not rounded; the tests allow a difference of 10⁻⁹. A month starts at 00:00:00 UTC on its first day. calendar.timegm, or datetime with timezone.utc, gives you the boundaries.

Examples

months = [(2024, 1), (2024, 2)]. February 2024 starts at 1706745600 and has 29 days.

incidents = [(1706742000, 1706749200),   # 31 Jan 23:00 to 1 Feb 01:00
             (1706747400, 1706751000)]   # 1 Feb 00:30 to 1 Feb 01:30

→ {(2024, 1): 99.86559139784946,   # 3,600 s down out of 2,678,400
   (2024, 2): 99.78448275862068}   # 5,400 s down out of 2,505,600

Constraints

Up to 5 × 10⁴ incidents and 24 months, with no month listed twice. Timestamps are integers and an incident may lie partly or wholly outside the requested months. Unix time has no leap seconds, so every day is 86,400 s; months are 28 to 31 days and December is followed by January of the next year.

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