Music streaming app~15 min2s · 256 MBtarget O(n) time, O(n) spacehashing
A music app shuffles a queue of tracks. Listeners complain about hearing the same track twice in a short time, so the app skips a track that played recently.
"Recently" counts tracks that really played, not tracks in the queue. A skipped track is never heard, so it does not count as played and does not restart the clock.
Write play_order(queue, gap).
queue from the front. Each entry is a track id.gap tracks that played. Otherwise it plays.gap = 0, nothing is skipped.Input: queue = [5, 3, 5, 8, 3, 5, 9, 5], gap = 2
Output: [5, 3, 8, 5, 9]The trace keeps, for each track, the position in the played list where it last played.
| Queue entry | Track | Played so far | Last played at | Distance | Result |
|---|---|---|---|---|---|
| 0 | 5 | none | none | none | plays at 0 |
| 1 | 3 | 5 | none | none | plays at 1 |
| 2 | 5 | 5, 3 | 0 | 2 | skipped |
| 3 | 8 | 5, 3 | none | none | plays at 2 |
| 4 | 3 | 5, 3, 8 | 1 | 2 | skipped |
| 5 | 5 | 5, 3, 8 | 0 | 3 | plays at 3 |
| 6 | 9 | 5, 3, 8, 5 | none | none | plays at 4 |
| 7 | 5 | 5, 3, 8, 5, 9 | 3 | 2 | skipped |
The distance is the number of tracks played so far minus the position of the last play. A track is skipped when the distance is at most 2. The output is [5, 3, 8, 5, 9].
Input: queue = [7, 7, 7, 7], gap = 0
Output: [7, 7, 7, 7]With gap = 0, every track plays, even repeats.
Input: queue = [1, 2, 1, 2], gap = 1
Output: [1, 2, 1, 2]The second 1 is two tracks after the first, and with gap = 1 only the very last track counts. So it plays, and so does the second 2.
1 ≤ queue.length ≤ 100,000 (tracks in the queue)1 ≤ queue[i] ≤ 1,000,000 (track ids)0 ≤ gap ≤ 100,000 (tracks that must pass before a track may repeat)Looking back through the last gap played tracks for every entry costs about n × gap, up to 10^10. A map from each track to the position where it last played answers "heard within the last gap tracks?" with one lookup and one subtraction.