Music streaming app~25 min2s · 256 MBtarget O(n log k) time, O(n) spaceclassic twin: lc-767heaps
A music streaming app builds a playlist from the tracks a listener saved. Each track has an artist code, written as a small letter. Listeners dislike two tracks by the same artist in a row.
Your team lead asks: "Can you order the tracks so that no artist plays twice in a row?" The order must be the same every time you build it, so the app can test it.
Write order_playlist(artists).
artists is a string of small letters. Each letter is one track, and the letter is its artist code.Input: artists = "aabbc"
Output: "ababc"The table shows, for each slot, the codes that can be taken with their tracks left, and the code taken.
| Slot | Previous code | Codes that can be taken (tracks left) | Taken |
|---|---|---|---|
| 1 | none | a (2), b (2), c (1) | a |
| 2 | a | b (2), c (1) | b |
| 3 | b | a (1), c (1) | a |
| 4 | a | b (1), c (1) | b |
| 5 | b | c (1) | c |
Input: artists = "aaab"
Output: ""Three tracks of one code cannot be kept apart by one other track.
Input: artists = "cab"
Output: "abc"All counts are 1, so the smaller letter goes first in every slot.
1 ≤ length of artists ≤ 100,000, and every letter is a to z.A playlist of 100,000 tracks has 100,000 slots. Counting the text that is left for each of the 26 codes in each slot costs about 130 billion steps.
A heap of 26 codes gives the best code in a few steps. That is about 100,000 slots of a few heap operations.