Music streaming app~22 min2s · 256 MBtarget O(n log k) time, O(k) spaceheaps
You work on a music streaming app. Play events from many servers reach a collector, each with a timestamp.
The events are almost in time order. Network delays make an event arrive a little early or late. It never arrives more than k places away from where it belongs.
Your team lead asks: "Release the events in time order as they arrive, holding back as few as possible." A collector sees up to 100,000 events, and k is usually small.
Write release_in_order(events, k).
events[i] is the timestamp of the event that arrived i-th.k places from the position it takes when the timestamps are sorted. For equal timestamps, any order of the equal ones counts.If k is 0, the events are already in order.
Input: events = [3, 1, 2, 6, 4, 5, 9, 7, 8], k = 2
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]The collector holds k = 2 events. For each new event, it adds the event and releases the smallest one held.
| New event | Smallest released | Held afterwards |
|---|---|---|
| start | 1, 3 | |
| 2 | 1 | 2, 3 |
| 6 | 2 | 3, 6 |
| 4 | 3 | 4, 6 |
| 5 | 4 | 5, 6 |
| 9 | 5 | 6, 9 |
| 7 | 6 | 7, 9 |
| 8 | 7 | 8, 9 |
| end | 8, then 9 |
Input: events = [2, 1, 4, 3], k = 1
Output: [1, 2, 3, 4]Input: events = [1, 2, 3], k = 0
Output: [1, 2, 3]1 ≤ len(events) ≤ 100,000, and each timestamp is from 0 to 1,000,000.0 ≤ k < len(events)k places from its sorted position.Scanning all waiting events for the smallest, for every output position, costs about n × n / 2 comparisons. For 100,000 events that is 5 billion. Because no event is more than k places away, the next event to release is always among the next k + 1 events. A heap of only k + 1 events needs about log2(k + 1) steps for each event.