Monitoring~12 min2s · 256 MBtarget O(n log n) time, O(n) spacesorting
A monitoring system keeps alert tickets with the minutes each one took to answer. A nightly job sorts them with merge sort that works in passes, from the bottom up.
Pass 1 merges neighbouring tickets into sorted pairs. Pass 2 merges neighbouring pairs into sorted runs of four, and each pass doubles the width of the runs. A run at the end of the list that has no partner stays as it is for that pass.
Support wants to see the list after a given number of passes.
Write list_after_passes(times, passes).
times[i] is the answer time of the i-th ticket.passes passes. With 0 passes, return the list unchanged. More passes than the list needs leave the list sorted.Input: times = [9, 4, 7, 1, 8, 3, 6, 2], passes = 2
Output: [1, 4, 7, 9, 2, 3, 6, 8]Pass 1 gives [4, 9, 1, 7, 3, 8, 2, 6]. Pass 2 merges [4, 9] with [1, 7], and then [3, 8] with [2, 6]. The table shows the first of those two merges.
| Step | Left waiting | Right waiting | Taken | Merged so far |
|---|---|---|---|---|
| 1 | [4, 9] | [1, 7] | 1 from the right | [1] |
| 2 | [4, 9] | [7] | 4 from the left | [1, 4] |
| 3 | [9] | [7] | 7 from the right | [1, 4, 7] |
| 4 | [9] | [] | 9 from the left | [1, 4, 7, 9] |
Input: times = [5, 2, 8, 1, 9], passes = 3
Output: [1, 2, 5, 8, 9]Pass 1 gives [2, 5, 1, 8, 9], and the 9 has no partner. Pass 2 gives [1, 2, 5, 8, 9]. Pass 3 merges that run with nothing and leaves it.
Input: times = [4, 4, 1], passes = 0
Output: [4, 4, 1]No pass has run, so nothing has moved.
0 ≤ times.length ≤ 50,000 (tickets)0 ≤ times[i] ≤ 1,000,000 (minutes)0 ≤ passes ≤ 20Sorting each block of 2^passes values by insertion costs about n × 2^passes / 4 shifts. With 16 passes on 50,000 random values that is about 6 × 10^8. Merging costs n per pass, so 16 passes cost about 800,000 steps.