Parcel-delivery app~20 min2s · 256 MBtarget O(n log n) time, O(n) spaceintervals · sorting
A parcel hub books unloading slots at one dock. Each booking is a pair of minutes, a start and an end. Bookings can overlap.
The dock crew cannot leave and come back within a short break. If the gap between two bookings is at most buffer minutes, the crew stays, and the bookings count as one busy block. You want the list of busy blocks for the day.
Write busy_blocks(slots, buffer).
slots[i] = [start, end] is a booking, with start < end. The list is in no particular order.buffer minutes after the other ends. A block can chain many bookings.[start, end] pairs, where start is the earliest start and end is the latest end in the block. List them from the earliest start.Input: slots = [[9, 12], [1, 3], [2, 5], [7, 8]], buffer = 1
Output: [[1, 5], [7, 12]]A block grows while the next booking starts at most buffer minutes after the block ends.
| Order | Slot | Gap after the block | Block after the slot |
|---|---|---|---|
| 1 | [1, 3] | new block | [1, 3] |
| 2 | [2, 5] | negative: overlap | [1, 5] |
| 3 | [7, 8] | 2, above the buffer 1 | closes [1, 5]; new block [7, 8] |
| 4 | [9, 12] | 1, within the buffer | [7, 12] |
After sorting, the bookings are [1, 3], [2, 5], [7, 8] and [9, 12], and buffer = 1. The table walks through them.
Input: slots = [[5, 6]], buffer = 0
Output: [[5, 6]]One booking is one block.
Input: slots = [[1, 2], [2, 3], [4, 5]], buffer = 0
Output: [[1, 3], [4, 5]]With buffer = 0, bookings that touch, such as [1, 2] and [2, 3], still merge. The gap to [4, 5] is 1, so it stays apart.
1 ≤ slots.length ≤ 100,000 (bookings)0 ≤ start < end ≤ 1,000,000,000 (minutes)0 ≤ buffer ≤ 1,000,000,000Merging any two bookings that qualify, again and again until none is left, costs about n³ steps in the worst case. After sorting by start, only the last block can still grow, so one sweep is enough. The sort costs about n × log n steps, 1.7 × 10^6 at n = 100,000.