Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-707linked-lists
A music app keeps the queue of songs as a two-way list. From any song the player can skip to the next song, or go back to the previous one. Song cards offer actions such as Add after this song and Remove from queue.
Each action must take constant time, because a queue can hold 100,000 songs and every tap should feel instant. Each song has a unique id.
Write run_playlist(commands, args).
commands[i] is one of the words below, and args[i] holds its numbers."addfirst" with [song]: put the song at the front. "addlast" with [song]: put it at the back."addafter" with [after, song]: put song right after the song after."remove" with [song]: take the song out of the queue."next" with [song]: answer the id of the song after it, or -1 for the last song."prev" with [song]: answer the id of the song before it, or -1 for the first song.after, and the song of "remove", "next" and "prev", are always in the queue. A removed song id may be added again later."next" and "prev", in order.Input: commands = ["addlast", "addlast", "addfirst", "addafter", "next", "prev", "remove", "next", "prev", "next"], args = [[10], [20], [5], [10, 15], [10], [20], [15], [10], [5], [20]]
Output: [15, 15, 20, -1, -1]| Step | Command | Queue | Answer |
|---|---|---|---|
| [1] | start | empty | |
| [4] | addlast 10 | 10 | |
| [4] | addlast 20 | 10 ⇄ 20 | |
| [4] | addfirst 5 | 5 ⇄ 10 ⇄ 20 | |
| [4] | addafter 10, 15 | 5 ⇄ 10 ⇄ 15 ⇄ 20 | |
| [6] | next 10 | 5 ⇄ 10 ⇄ 15 ⇄ 20 | 15 |
| [6] | prev 20 | 5 ⇄ 10 ⇄ 15 ⇄ 20 | 15 |
| [5] | remove 15 | 5 ⇄ 10 ⇄ 20 | |
| [6] | next 10 | 5 ⇄ 10 ⇄ 20 | 20 |
| [6] | prev 5 | 5 ⇄ 10 ⇄ 20 | -1 |
| [6] | next 20 | 5 ⇄ 10 ⇄ 20 | -1 |
Input: commands = ["addfirst", "next"], args = [[4], [4]]
Output: [-1]A queue of one song: nothing comes after it.
Input: commands = ["addlast", "addlast", "remove", "prev"], args = [[1], [2], [1], [2]]
Output: [-1]Song 1 was removed, so song 2 is the first song and has nothing before it.
1 ≤ commands.length = args.length ≤ 100,000args[i] has one or two numbers as described.Keeping the queue in an array and searching it for a song costs up to one step for each song, on every command. With 50,000 songs and 10^5 commands, that is about 5 × 10^9 steps.
A hash map from song id to node finds the song in one step, and the two-way pointers change the list in a few writes.