Music streaming app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-92linked-lists
A music app shows a playlist as a chain of nodes, from the first song to the last. A listener picks a stretch of the playlist, from position left to position right, and taps Flip.
The songs of that stretch play in reverse order, and every song outside it stays where it was. Positions start at 1. A playlist can hold up to 100,000 songs, and the app reuses the same nodes.
Write flip_stretch(head, left, right).
head is the first node of the playlist. Each node's val is a song id.left and right are positions counted from 1 at the head, with 1 ≤ left ≤ right ≤ the number of songs.left to position right in place, and return the head of the playlist. When left is 1, the head changes.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], left = 2, right = 4
Output: [10, 40, 30, 20, 50]| Step | prev | curr | next (saved) | Arrow turned | Chain so far |
|---|---|---|---|---|---|
| [2] before moves to position 1 | before = 10 | ||||
| [3] start | null | 20 | start = 20 | ||
| round 1 | null | 20 | 30 | 20 now points at null | 20 |
| round 2 | 20 | 30 | 40 | 30 now points at 20 | 30 → 20 |
| round 3 | 30 | 40 | 50 | 40 now points at 30 | 40 → 30 → 20 |
| [4] reconnect | 40 | 50 | 10 points at 40, and 20 points at 50 | 10 → 40 → 30 → 20 → 50 |
The stretch has 4 - 2 + 1 = 3 songs, so the loop runs three rounds. Two pointers change after it: the node before the stretch, and the old first node of the stretch.
Input: head = [7, 8, 9], left = 1, right = 3
Output: [9, 8, 7]The stretch is the whole playlist. The head changes, which is why a placeholder node before the head helps.
Input: head = [4, 6], left = 2, right = 2
Output: [4, 6]A stretch of one song reverses to itself.
1 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^61 ≤ left ≤ right ≤ number of nodesOne walk down the chain is 10^5 hops, far inside the time limit. A plan that walks from the head for every swap of two songs makes about m × n hops for a stretch of m songs. That is 5 × 10^9 for a whole playlist, which is too slow.
So reach position left once, turn the arrows of the stretch in one pass, and then fix the two ends. That is O(n) time and O(1) extra memory: a few pointers.