Ride-hailing app~20 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-328linked-lists
A ride-hailing app plans a shuttle route as a chain of stops. The shuttle makes two laps. On the first lap it serves the stops in odd positions: the 1st, 3rd, 5th and so on. On the second lap it serves the stops in even positions.
The planner must reorder the chain so that the odd positions come first and the even positions follow, with the order inside each group unchanged. A route can have up to 100,000 stops, and the planner reuses the same nodes.
Write odd_stops_first(head).
head is the first node of the route, or null when the route is empty. Each node's val is a stop id.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [10, 20, 30, 40, 50, 60, 70]
Output: [10, 30, 50, 70, 20, 40, 60]| Step | odd | even | Odd chain | Even chain |
|---|---|---|---|---|
| [1] | 10 | 20 | 10 | 20 |
| [3] | 30 | 20 | 10 → 30 | 20 |
| [3] | 30 | 40 | 10 → 30 | 20 → 40 |
| [3] | 50 | 40 | 10 → 30 → 50 | 20 → 40 |
| [3] | 50 | 60 | 10 → 30 → 50 | 20 → 40 → 60 |
| [3] | 70 | 60 | 10 → 30 → 50 → 70 | 20 → 40 → 60 |
| [4] | 10 → 30 → 50 → 70 | joined: 10 → 30 → 50 → 70 → 20 → 40 → 60 |
Positions 1, 3, 5 and 7 hold 10, 30, 50 and 70. Positions 2, 4 and 6 hold 20, 40 and 60.
Input: head = [8, 9, 4]
Output: [8, 4, 9]The odd positions hold 8 and 4, and the even position holds 9. The stop ids do not matter: 8 is even, but it is in position 1.
Input: head = [7]
Output: [7]One stop: nothing moves.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^6Reading each stop by position, with a walk from the head, costs about n² / 4 hops for each group. That is about 5 × 10^9 hops at this size.
Relinking the nodes as one walk costs about n / 2 loop steps.