Search~25 min2s · 256 MBtarget O((n + m) log (n + m)) time, O(n + m) spacegreedy
A search service logs the minutes at which query traffic spikes. To handle spikes, it can start a cache warm-up window. Each window is a fixed range of minutes, from a start minute to an end minute, and both ends count.
The operations team has a list of possible windows. A spike is handled when some chosen window covers its minute. The team wants to handle every spike with as few windows as possible, because each window uses servers.
Write fewest_windows_for_spikes(spikes, windows).
spikes lists the minutes of the spikes. A minute can appear more than once.windows[j] is [start, end] with start <= end: a window that covers every minute from start to end, both included.-1 if no choice of windows covers them all.Input: spikes = [1,4,6,9,10], windows = [[0,3],[2,5],[4,7],[5,6],[8,12],[9,10]]
Output: 3The solution looks at the earliest spike that is not yet covered. Among all windows that start at or before that spike, it takes the one that ends last, and then skips every spike that window covers.
| Spike to cover | Windows that start at or before it | Window taken | Spikes covered |
|---|---|---|---|
| 1 | [0,3] |
[0,3], ends at 3 |
1 |
| 4 | [2,5], [4,7] |
[4,7], ends at 7 |
4 and 6 |
| 9 | [5,6], [8,12], [9,10] |
[8,12], ends at 12 |
9 and 10 |
Three windows cover all the spikes, so the answer is 3.
Input: spikes = [1,5], windows = [[0,2],[4,4]]
Output: -1The window [0,2] covers minute 1, but no window covers minute 5, because [4,4] ends one minute earlier. The answer is -1.
Input: spikes = [2,3,4], windows = [[0,10],[1,3]]
Output: 1The window [0,10] covers all three spikes, so one window is enough.
1 ≤ len(spikes) ≤ 100,000, and 0 ≤ spikes[i] ≤ 1,000,000,0000 ≤ len(windows) ≤ 100,000, and every window is [start, end] with 0 ≤ start ≤ end ≤ 1,000,000,000Trying every set of windows costs 2 to the power of 100,000. Even checking each spike against each window costs about 10,000,000,000 pairs. After sorting, one pass over the spikes and the windows costs about 200,000 steps.