Payments app~22 min2s · 256 MBtarget O(n log n) time, O(1) spaceheaps
You work on a payments app. At the end of the day, a job lists the transfer amounts, with refunds as negative numbers. The report needs them from the largest to the smallest. The job runs on a small device with almost no spare memory, so it must sort the list inside one array.
Your team lead asks: "Give me the amounts, largest first, without a second array of the same size." The list can hold 20,000 amounts. Write the sort yourself with a heap, and use no library sort.
Write sort_transfers(amounts).
amounts[i] is a transfer amount, in units. A refund is negative.Input: amounts = [40, -15, 70, 5, -15, 90, 20]
Output: [90, 70, 40, 20, 5, -15, -15]The array is read as a tree: the children of position i are at 2i + 1 and 2i + 2. The table shows the array after each step.
| Step | Array |
|---|---|
| start | 40, -15, 70, 5, -15, 90, 20 |
| build: sift down position 2 | 40, -15, 20, 5, -15, 90, 70 |
| build: sift down position 1 | 40, -15, 20, 5, -15, 90, 70 |
| build: sift down position 0 | -15, -15, 20, 5, 40, 90, 70 |
| move the smallest to position 6 | -15, 5, 20, 70, 40, 90, -15 |
| move the smallest to position 5 | 5, 40, 20, 70, 90, -15, -15 |
| move the smallest to position 4 | 20, 40, 90, 70, 5, -15, -15 |
| move the smallest to position 3 | 40, 70, 90, 20, 5, -15, -15 |
| move the smallest to position 2 | 70, 90, 40, 20, 5, -15, -15 |
| move the smallest to position 1 | 90, 70, 40, 20, 5, -15, -15 |
Input: amounts = [3, 1, 2]
Output: [3, 2, 1]Input: amounts = [7]
Output: [7]1 ≤ len(amounts) ≤ 20,000-1,000,000,000 ≤ amounts[i] ≤ 1,000,000,000Selecting the largest by a scan, once for every position, costs about n × n / 2 comparisons. For 20,000 amounts that is 200 million. A heap finds the next item in about 14 steps, so the whole sort needs about 20,000 × 14 = 280,000 steps. A heap lives inside the array it sorts, so it needs no extra memory.