Music streaming app~30 min2s · 256 MBtarget O(n²) time, O(n) spaceclassic twin: lc-31backtracking
A music app has a playlist of tracks, each with its own number. The "next shuffle" button moves to the next ordering of the same tracks in dictionary order. After the last ordering, it goes back to the first one, which has the tracks in increasing order.
A listener presses the button many times, and the app must show the playlist at once, without pressing a billion times. You find the order after a given number of presses.
Write playlist_after_skips(order, skips).
order lists the track numbers in the current order. All numbers are different.skips presses of the button.Input: order = [2,3,1], skips = 3
Output: [1,2,3]The solution does not press the button. It finds where the current order sits in the list of all orderings, adds the presses, wraps round, and builds the order at the new position.
| Position | Track | Smaller tracks to the right | Weight | Contribution |
|---|---|---|---|---|
| 0 | 2 | 1 | 2! = 2 | 2 |
| 1 | 3 | 1 | 1! = 1 | 1 |
| 2 | 1 | 0 | 0! = 1 | 0 |
The current order is at place 3 of the list 123, 132, 213, 231, 312, 321, counting from 0. Adding 3 gives 6. There are 6 orderings, so the place wraps to 0, which is [1,2,3].
Input: order = [1,3,2], skips = 0
Output: [1,3,2]With no presses, the order stays as it is.
Input: order = [5,9,2,7], skips = 100000
Output: [2,7,5,9]Four tracks have 24 orderings, so 100,000 presses wrap round 4,166 times. Only the remainder, 16 presses after the current order, matters, and it lands on [2,7,5,9].
1 ≤ len(order) ≤ 15, every track number is between 1 and 1,000,000, and all track numbers are different0 ≤ skips ≤ 1,000,000,000Pressing the button one at a time costs about a billion steps, and each step costs up to 15 operations. Fifteen tracks have 15 factorial orderings, about 1.3 × 10^12, so the place of an order fits in a 64-bit number. Finding the place and the new order costs about 15 times 15 steps.