Music streaming app~15 min2s · 256 MBtarget O(limit) time, O(limit) spacemerge-sorted · two-pointers
A music app lets you queue two playlists together. Each playlist is already sorted by track rank, the app's own popularity order, and no rank repeats inside one playlist.
The merged queue must keep that order. A track that is in both playlists plays once. The player only needs the first few tracks, so the queue stops at a limit.
Write merge_playlists(a, b, limit).
a and b are lists of track ranks, each in strictly increasing order. Either list may be empty.limit tracks of the merged list, or all of them when there are fewer.Input: a = [2, 5, 9, 14], b = [3, 5, 8, 14, 20], limit = 6
Output: [2, 3, 5, 8, 9, 14]The trace keeps one read position in each list.
| Step | Front of a |
Front of b |
Taken | Queue after the step |
|---|---|---|---|---|
| 1 | 2 | 3 | 2 from a |
2 |
| 2 | 5 | 3 | 3 from b |
2, 3 |
| 3 | 5 | 5 | 5 from both | 2, 3, 5 |
| 4 | 9 | 8 | 8 from b |
2, 3, 5, 8 |
| 5 | 9 | 14 | 9 from a |
2, 3, 5, 8, 9 |
| 6 | 14 | 14 | 14 from both | 2, 3, 5, 8, 9, 14 |
The queue now holds 6 tracks, the limit, so the output is [2, 3, 5, 8, 9, 14]. Tracks 5 and 14 are in both playlists and appear once.
Input: a = [], b = [4, 6], limit = 5
Output: [4, 6]The first playlist is empty, so the queue is the second playlist.
Input: a = [1, 2, 3], b = [1, 2, 3], limit = 2
Output: [1, 2]The playlists are identical, so each track appears once, and the limit cuts the queue after 2 tracks.
0 ≤ a.length, b.length ≤ 100,000 (tracks in a playlist)1 ≤ a[i], b[j] ≤ 1,000,000 (track ranks), each list strictly increasing1 ≤ limit ≤ 200,000 (tracks the player asks for)Picking the smallest remaining track again and again costs limit × (n + m), about 4 × 10^10 at the limits. Sorting both lists together would cost more than a merge needs. Both lists are already sorted, so a single pass with one position in each list does the merge in n + m steps.