Payments app~25 min2s · 256 MBtarget O(n log n) time, O(log n) spaceclassic twin: lc-148linked-lists · sorting
A payments app keeps the day's ledger entries as a chain of nodes, in the order they arrived. Each node holds the amount of one entry, in minor units.
The reconciliation job needs the entries in ascending order of amount. A chain has no index to jump to, so a sort that swaps entries by position is out of reach. The chain can hold up to 100,000 entries, and the job reuses the same nodes.
Write sort_entries(head).
head is the first node of the chain, or null when the chain is empty. Each node's val is an amount.val. Equal amounts may appear in any order, because they cannot be told apart.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [48, 12, 35, 7, 29, 3]
Output: [3, 7, 12, 29, 35, 48]| Step | Chain | Split into | Merged result |
|---|---|---|---|
| [2] | [48, 12, 35, 7, 29, 3] | [48, 12, 35] and [7, 29, 3] | |
| [2] | [48, 12, 35] | [48, 12] and [35] | |
| [2] | [48, 12] | [48] and [12] | |
| [4] | [48] and [12] | [12, 48] | |
| [4] | [12, 48] and [35] | [12, 35, 48] | |
| [2] | [7, 29, 3] | [7, 29] and [3] | |
| [2] | [7, 29] | [7] and [29] | |
| [4] | [7] and [29] | [7, 29] | |
| [4] | [7, 29] and [3] | [3, 7, 29] | |
| [4] | [12, 35, 48] and [3, 7, 29] | [3, 7, 12, 29, 35, 48] |
Input: head = [5, 5, 1]
Output: [1, 5, 5]Equal amounts stay next to each other.
Input: head = []
Output: []An empty chain is already sorted.
0 ≤ number of nodes ≤ 10^50 ≤ node.val ≤ 10^6Inserting each entry into a sorted chain by scanning from the head costs up to n² / 2 comparisons. That is about 5 × 10^9 at this size, and 2.5 × 10^9 on average for random amounts.
A sort that halves the chain each time has about log₂ n = 17 levels, and each level walks every node once to split and once to merge. That is about 3.4 × 10^6 steps.