Music streaming app~25 min2s · 256 MBtarget O(n) time, O(1) spaceclassic twin: lc-61linked-lists · two-pointers
A music app has a Rotate button. It moves the last k songs of a playlist to the front, keeping their order, so that the end of the playlist opens the next round.
When k is larger than the playlist, the rotation goes round and round. The playlist is a chain of nodes with up to 100,000 songs, and the app reuses the same nodes.
Write rotate_playlist(head, k).
head is the first node of the playlist, or null when the playlist is empty. Each node's val is a song id.k is the number of songs to move, and it may be larger than the length of the playlist.k songs to the front, in the same order, and return the new head. A rotation by the full length changes nothing.The tests give head as the list of values from the head, and read your answer the same way.
Input: head = [1, 2, 3, 4, 5], k = 2
Output: [4, 5, 1, 2, 3]| Step | slow | fast | What happens |
|---|---|---|---|
| [1] | walk once: n = 5, and the last song is 5 | ||
| [2] | k = 2 mod 5 = 2 | ||
| [3] | 1 | 1 | both start on the head |
| [3] | 1 | 3 | fast moves k = 2 songs ahead |
| [3] | 2 | 4 | both move one song |
| [3] | 3 | 5 | fast is on the last song, so slow is on the new last song, 3 |
| [4] | new head = 4. Then 3 → null, and 5 → 1 |
The last k = 2 songs, 4 and 5, move to the front. The gap of 2 between slow and fast is what finds them.
Input: head = [10, 20, 30], k = 4
Output: [30, 10, 20]k is larger than the playlist. Rotating by 4 is the same as rotating by 4 mod 3 = 1.
Input: head = [8, 9], k = 2
Output: [8, 9]Rotating by the full length returns the same playlist.
0 ≤ number of nodes ≤ 10^51 ≤ node.val ≤ 10^60 ≤ k ≤ 10^9You cannot rotate one song at a time k times, because 10^9 rotations is far too many, and each one walks the chain. Rotating by n songs gives the same playlist back, so only k mod n matters. That is below 10^5.
Even then, moving the last song to the front k mod n times costs up to n hops each: about 5 × 10^9 at this size. So find the cut point in one walk, with two pointers that are k mod n songs apart.