Music streaming app~20 min2s · 256 MBtarget O(n log k) time, O(k) spaceclassic twin: lc-2099top-k · heaps
A music app lets listeners pin their favourites. Each playlist track has a rating from 0 to 1,000,000, and a listener asks for the k best-rated tracks of a playlist.
The app must not reorder the playlist. It shows the winners in the order they appear in the playlist, so the listener can still read them as the playlist's own story. A playlist can hold up to 100,000 tracks.
Write best_tracks(ratings, k).
ratings[i] is the rating of the track at position i. Positions start at 0.k highest-ranked tracks. Return their positions, in increasing order of position.Input: ratings = [7, 3, 9, 4, 9, 1], k = 3
Output: [0, 2, 4]Keep a heap that never holds more than 3 tracks, with the weakest on top. Each row shows the heap after the track is added and, if the heap had 4 tracks, after the weakest one has left. The tracks are listed from the weakest to the strongest.
| Position (rating) | Heap after the step | Leaves |
|---|---|---|
| 0 (7) | 0 | |
| 1 (3) | 1, 0 | |
| 2 (9) | 1, 0, 2 | |
| 3 (4) | 3, 0, 2 | position 1 (rating 3) |
| 4 (9) | 0, 4, 2 | position 3 (rating 4) |
| 5 (1) | 0, 4, 2 | position 5, the new track itself |
Positions 2 and 4 both have rating 9. The tie goes to the smaller position, so position 4 is the weaker of the two. The heap holds positions 0, 2 and 4. The answer lists them in increasing order of position.
Input: ratings = [5, 5, 5, 5], k = 2
Output: [0, 1]All four tracks tie, so the earlier ones rank higher.
Input: ratings = [2, 8], k = 2
Output: [0, 1]k equals the number of tracks, so every track is chosen.
1 ≤ length of ratings ≤ 10^50 ≤ ratings[i] ≤ 10^61 ≤ k ≤ length of ratingsWith 100,000 tracks, picking the best one by scanning the playlist and doing that k times costs n × k steps. For k = 50,000 that is 5 × 10^9 steps, which is far too slow.
A heap that never holds more than k tracks costs about log k per track. That is n log k in all, and the heap needs room for only k tracks.