Monitoring~15 min2s · 256 MBtarget O(n d) time, O(n) spaceclassic twin: lc-147sorting
A log collector receives lines from a service almost in time order. Network delays move a line, but never more than 5 places from where it belongs in the sorted order.
The collector keeps the lines in a linked chain. Before it saves the chain, it must put the lines in order of timestamp, earliest first.
You get the chain from its first line. Sort it, and return the sorted chain.
Write insertion_sort_list(head).
head is the first node of a chain, and each node's val is a timestamp in milliseconds. head is null for an empty chain.val, smallest first. Lines with equal timestamps keep their arrival order.Input: head = [20, 10, 30, 50, 40, 60]
Output: [10, 20, 30, 40, 50, 60]Insertion sort keeps the front of the chain in order and inserts each next line into it.
| Next line | Larger lines it passes | Front part after the insert |
|---|---|---|
| 10 | 1 (the 20) | [10, 20] |
| 30 | 0 | [10, 20, 30] |
| 50 | 0 | [10, 20, 30, 50] |
| 40 | 1 (the 50) | [10, 20, 30, 40, 50] |
| 60 | 0 | [10, 20, 30, 40, 50, 60] |
Two lines moved, one place each, so the sort did only 2 shifts.
Input: head = []
Output: []An empty chain stays empty.
Input: head = [5, 5, 3]
Output: [3, 5, 5]The line with timestamp 3 moves in front of both 5s.
0 ≤ chain length ≤ 100,000 (log lines)0 ≤ val ≤ 1,000,000,000 (milliseconds)Inserting every line by walking the chain from its first node costs about n × n / 2 steps, which is 5 × 10^9 at n = 100,000. A line is at most 5 places out. An insertion that starts from the sorted end moves each line at most 5 places, so the whole sort costs at most about 5 × n steps.