Maps app~25 min2s · 256 MBtarget O(n log r) time, O(n) spacesorting · merge-sorted
A maps app collects location pings from many phones. Each phone sends its pings as a batch, already sorted by time, and the server appends the batches to one list. The whole list is therefore a series of sorted stretches, and a stretch ends where a ping is earlier than the one before it. The app wants all pings in time order.
Write sort_by_merging_runs(values).
values is a list of ping times made of sorted stretches, joined one after the other.Input: values = [2, 5, 9, 1, 4, 3, 3, 8]
Output: [1, 2, 3, 3, 4, 5, 8, 9]Split the list into stretches where a value drops. Then merge neighbouring stretches in rounds until one is left.
| Round | Runs at the start | Runs after merging neighbours |
|---|---|---|
| 1 | [[2, 5, 9], [1, 4], [3, 3, 8]] | [[1, 2, 4, 5, 9], [3, 3, 8]] |
| 2 | [[1, 2, 4, 5, 9], [3, 3, 8]] | [[1, 2, 3, 3, 4, 5, 8, 9]] |
The single stretch left is [1, 2, 3, 3, 4, 5, 8, 9].
Input: values = [1, 2, 3, 4]
Output: [1, 2, 3, 4]There is one stretch, so nothing needs merging: [1, 2, 3, 4].
Input: values = [4, 3, 2, 1]
Output: [1, 2, 3, 4]Every value is its own stretch, so merging does all the work: [1, 2, 3, 4].
0 ≤ values.length ≤ 100,000 (pings)0 ≤ values[i] ≤ 1,000,000 (seconds)Inserting each value into place costs about n × n steps in the worst case, which is 10^10 at n = 100,000. Merging r stretches in rounds costs n per round and log r rounds.