Bank app~20 min2s · 256 MBtarget O(n log c) time, O(n) spacesorting
A bank app exports a ledger of posting times, in seconds. The export is too large to sort in memory, so a first job wrote it as chunks. Each chunk was sorted when it was written, but the chunks are in no order relative to one another.
A second job must join the chunks into one export in posting order. It merges neighbouring chunks two at a time, so it never sorts the whole file again.
Write merge_sorted_chunks(entries, lengths).
entries holds all chunks one after another. lengths[c] is the number of entries in chunk c, and the lengths add up to len(entries).Input: entries = [3, 8, 12, 1, 9, 4, 5, 6, 20], lengths = [3, 2, 4]
Output: [1, 3, 4, 5, 6, 8, 9, 12, 20]The chunks are [3, 8, 12], [1, 9] and [4, 5, 6, 20]. The first level merges the first two chunks, and the third has no partner. The table shows the first merge.
| Step | Left waiting | Right waiting | Taken | Merged so far |
|---|---|---|---|---|
| 1 | [3, 8, 12] | [1, 9] | 1 from the right | [1] |
| 2 | [3, 8, 12] | [9] | 3 from the left | [1, 3] |
| 3 | [8, 12] | [9] | 8 from the left | [1, 3, 8] |
| 4 | [12] | [9] | 9 from the right | [1, 3, 8, 9] |
| 5 | [12] | [] | 12 from the left | [1, 3, 8, 9, 12] |
The second level merges [1, 3, 8, 9, 12] with [4, 5, 6, 20].
Input: entries = [5, 5, 2, 5], lengths = [2, 2]
Output: [2, 5, 5, 5]Equal posting times are kept.
Input: entries = [10, 20, 30], lengths = [3]
Output: [10, 20, 30]One chunk is already the whole export.
0 ≤ entries.length ≤ 50,000 (ledger lines)0 ≤ lengths.length ≤ 50,000 (chunks), and 1 ≤ lengths[c] ≤ 50,0000 ≤ entries[i] ≤ 1,000,000,000 (seconds)entries.length, and every chunk is sorted.Taking the smallest remaining entry n times costs about n × n / 2 comparisons, which is 1,249,975,000 at n = 50,000. Merging the chunks costs n for each level of the merge, and there are about log₂ c levels for c chunks.