Monitoring~20 min2s · 256 MBtarget O(n + m) time, O(1) spaceclassic twin: lc-21merge-sorted · linked-lists
A monitoring system collects the log entries of one service on two shards. Each shard keeps its entries as a chain of nodes in time order: each node holds a timestamp in seconds and a pointer to the next entry. Timestamps can repeat, because a shard writes several entries in the same second.
An incident page needs one chain for the whole service, still in time order. Memory is tight during an incident, so the page relinks the existing nodes instead of copying them. When two entries share a timestamp, the first shard's entry goes first. Each shard holds up to 50,000 entries.
Write merge_log_chains(first, second).
first is the head of the first shard's chain, and second is the head of the second shard's chain. Either may be null. Each node's val is a timestamp, and each chain is in non-decreasing order.The tests give each chain as the list of values from its head, and read your answer the same way.
Input: first = [100, 104, 104, 130], second = [101, 104, 120]
Output: [100, 101, 104, 104, 104, 120, 130]| first front | second front | Linked next | Merged chain so far |
|---|---|---|---|
| 100 | 101 | 100, from first | 100 |
| 104 | 101 | 101, from second | 100, 101 |
| 104 | 104 | 104, from first: a tie goes to first | 100, 101, 104 |
| 104 | 104 | 104, from first | 100, 101, 104, 104 |
| 130 | 104 | 104, from second | 100, 101, 104, 104, 104 |
| 130 | 120 | 120, from second | 100, 101, 104, 104, 104, 120 |
| 130 | null | the rest of first: 130 | 100, 101, 104, 104, 104, 120, 130 |
Input: first = [], second = [5, 9]
Output: [5, 9]The first shard had no entries, so the answer is the second chain as it is.
Input: first = [50, 60], second = [10, 20, 30]
Output: [10, 20, 30, 50, 60]Every entry of the second shard comes first. When the second chain runs out, the whole first chain is linked on in one step.
0 ≤ length of first, length of second ≤ 5 × 10^40 ≤ node.val ≤ 10^9Both chains together hold up to 10^5 entries. Reading every timestamp into an array and sorting is about 1.7 × 10^6 comparisons, which is fast, but it copies every entry. A sort that moves one value at a time is up to 2.5 × 10^9 moves here.
Each chain is already sorted. One walk with a cursor on each front links every node once: O(n + m) time, and no copy.