Monitoring~30 min2s · 256 MBtarget O(n log k) time, O(k) spaceclassic twin: lc-23k-way-merge · heaps
A monitoring system collects events from many services. Each service sends its events in time order, so each stream is already sorted. The dashboard needs one timeline of all the events.
For the timeline, your team lead wants to know which service each event came from. When two events have the same time, the service with the lower number goes first. The streams hold up to 200,000 events in all, and there can be up to 5,000 streams.
Write merged_sources(streams).
streams[i] is the list of event times of service i, in non-decreasing order. A stream can be empty.Input: streams = [[1, 5, 9], [2, 5], [3, 4, 8]]
Output: [0, 1, 2, 2, 0, 1, 2, 0]Keep a heap with the next event of each stream. Each entry is a time, a service number and a position.
| Pop | Event (time, service) | Pushed next | Heap after the step |
|---|---|---|---|
| 1 | 1 from service 0 | 5 from service 0 | (2, 1), (3, 2), (5, 0) |
| 2 | 2 from service 1 | 5 from service 1 | (3, 2), (5, 0), (5, 1) |
| 3 | 3 from service 2 | 4 from service 2 | (4, 2), (5, 0), (5, 1) |
| 4 | 4 from service 2 | 8 from service 2 | (5, 0), (5, 1), (8, 2) |
| 5 | 5 from service 0 | 9 from service 0 | (5, 1), (8, 2), (9, 0) |
| 6 | 5 from service 1 | nothing: stream 1 is done | (8, 2), (9, 0) |
| 7 | 8 from service 2 | nothing | (9, 0) |
| 8 | 9 from service 0 | nothing | empty |
The two events at time 5 come out as service 0, then service 1: the lower number goes first.
Input: streams = [[], [4, 4], [4]]
Output: [1, 1, 2]Service 0 sent nothing. All three events are at time 4. Service 1 comes before service 2, and both of its events come first.
Input: streams = [[7]]
Output: [0]One stream with one event.
1 ≤ number of streams ≤ 5,0000 ≤ length of one stream ≤ 2 × 10^5, and at most 2 × 10^5 events in all0 ≤ time ≤ 10^9Looking at the front of every stream for each of the 200,000 events costs 200,000 × 5,000 = 10^9 steps. A heap of the fronts has at most 5,000 entries, so each event costs about 12 steps.
Putting all the events into one list and sorting it also works at this size. The heap does not need all the events in memory at once, and it can start producing the timeline at once.