1383. At Least K Busy Spans
A power grid logs when each generator was running. Each entry of intervals is a half-open range [start, end) during which one generator was on, and the ranges may overlap freely. At any instant the number of active generators is the number of ranges that cover it; a range that ends exactly at t no longer counts at t, while one that starts at t does.
Return all maximal spans [a, b) with a < b during which at least k generators are active, sorted by a. Maximal means that spans which touch are joined: if the count stays at least k across a shared boundary, that is one span, so no two returned spans share an endpoint. If there is no such time, return an empty list.
Sweep the +1 and -1 events in sorted order, processing all events at the same coordinate before looking at the count after it. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- intervals = [[1,5],[3,8],[6,9],[2,4]], k = 2
- Output:
- [[2,5],[6,8]]
- Explanation:
Counts are 1 on [1,2), 2 on [2,3), 3 on [3,4), 2 on [4,5), 1 on [5,6), 2 on [6,8) and 1 on [8,9); at least 2 holds on [2,5) and [6,8).
Example 2
- Input:
- intervals = [[0,3],[3,6]], k = 1
- Output:
- [[0,6]]
- Explanation:
The ranges touch at 3, the count never drops below 1, so they form the single span [0,6).
Example 3
- Input:
- intervals = [[0,2],[4,6]], k = 2
- Output:
- []
- Explanation:
The two generators never run together, so no span has two active.
Constraints
1 ≤ intervals.length (n) ≤ 500
1 ≤ k ≤ n
0 ≤ start < end ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n log n)
- Space
- O(n)