Parcel-delivery app~15 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · sorting
A delivery app lets a courier accept timed slots: each slot has a start minute and an end minute. Slots are accepted in any order, so some of them overlap.
The courier also needs a travel buffer between jobs. A slot is a problem when it starts before an earlier slot has ended plus the buffer. Support wants to know how many slots are in that position.
Write count_clashing_slots(starts, ends, buffer).
i runs from minute starts[i] to minute ends[i].starts[j] < ends[i] + buffer, where i is the earlier slot.Input: starts = [540, 600, 570, 660, 555], ends = [570, 640, 600, 700, 590], buffer = 10
Output: 3The trace sorts the slots by start and keeps the latest end so far.
| Slot | Start | End | Latest end before it | Clashes? | Latest end after it |
|---|---|---|---|---|---|
| 0 | 540 | 570 | none | no | 570 |
| 4 | 555 | 590 | 570 | yes: 555 < 570 + 10 | 590 |
| 2 | 570 | 600 | 590 | yes: 570 < 590 + 10 | 600 |
| 1 | 600 | 640 | 600 | yes: 600 < 600 + 10 | 640 |
| 3 | 660 | 700 | 640 | no: 660 is not below 650 | 700 |
Three slots clash, so the output is 3.
Input: starts = [0, 30], ends = [30, 60], buffer = 0
Output: 0The second slot starts at minute 30, exactly when the first one ends. With no buffer they only touch.
Input: starts = [100, 0], ends = [200, 50], buffer = 60
Output: 1The list is not in start order. Sorted, the slot from 0 to 50 comes first, and the slot starting at 100 is below 50 + 60.
1 ≤ starts.length ≤ 100,000 (slots in a month); ends has the same length0 ≤ starts[i] < ends[i] ≤ 1,000,000,000 (minutes from the start of the month)0 ≤ buffer ≤ 1,000 (minutes)Checking every slot against every earlier slot costs about n × n / 2 steps, about 5 × 10^9 at n = 100,000. Sorting costs n log n. Once the slots are in start order, one number, the latest end so far, replaces the whole list of earlier slots.