Parcel-delivery app~35 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-25linked-lists
A parcel-delivery app loads a conveyor belt into trucks. Each truck takes k parcels, and the loaders place them so that each full group of k leaves the belt in reverse order.
When the parcels run out, the last group may hold fewer than k parcels. It is loaded in belt order, without reversing. The belt is a chain of nodes with up to 100,000 parcels, and the same nodes must be reused.
Write reverse_in_groups(head, k).
head is the first node of the belt, or null when the belt is empty. Each node's val is a parcel id.k is the size of a group.k consecutive nodes in place. Leave a last group of fewer than k nodes as it is.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [11, 12, 13, 14, 15], k = 2
Output: [12, 11, 14, 13, 15]| Round | group_prev | kth | group_next | Pointer work | The chain now |
|---|---|---|---|---|---|
| [1] | placeholder | placeholder → 11 → 12 → 13 → 14 → 15 | |||
| 1 | placeholder | 12 | 13 | 11 → 13, then 12 → 11; placeholder → 12; group_prev = 11 | 12 → 11 → 13 → 14 → 15 |
| 2 | 11 | 14 | 15 | 13 → 15, then 14 → 13; 11 → 14; group_prev = 13 | 12 → 11 → 14 → 13 → 15 |
| 3 | 13 | null | the walk of 2 nodes ends at null, so the last group is short: stop | return 12 → 11 → 14 → 13 → 15 |
The last group, 15, has one parcel and stays in place. Each round also finds the end of its group before it reverses anything.
Input: head = [21, 22, 23, 24, 25, 26], k = 3
Output: [23, 22, 21, 26, 25, 24]Two full groups, and no short group.
Input: head = [7, 8, 9], k = 4
Output: [7, 8, 9]The belt is shorter than one group, so nothing is reversed.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^91 ≤ k ≤ 10^5 (k may be larger than the number of nodes)A plan that swaps ids by walking from the head for every swap makes about n^2 / 2 hops in all. That is 5 × 10^9 at this size, whatever k is, which is too slow. So each group must be reversed by walking along it once.
A recursive solution makes one call per group. With k = 2 that is 50,000 nested calls, more than a default call stack holds in some languages. So write loops. Each node is visited twice, once to find the end of its group and once to turn it: O(n) time and O(1) extra memory.