Music streaming app~22 min2s · 256 MBtarget O(n) time, O(k) spaceat-most-k · sliding-window-variable
You work on a music streaming service. A listener's history is a list of the artist of each track played, in order. A wellness feature looks for the longest listening session that is varied enough.
A session is a run of consecutive tracks. It is varied when it has at most k different artists, and no artist plays more than cap times in it. Your team lead asks: "How long is the longest varied session?" A history can hold 100,000 tracks.
Write longest_session(artists, k, cap).
artists[i] is the artist id of the i-th track played.k distinct artists, and each artist appears at most cap times in it.Input: artists = [1, 2, 1, 3, 1, 2, 2, 4], k = 2, cap = 3
Output: 3Slide a window along the history. Add the new track, and while the window breaks a limit, drop tracks from the left. The window is then the longest allowed session that ends at the new track.
| Track | Longest valid session ending here | Artists | Most plays of one artist | Length |
|---|---|---|---|---|
| 0 | [1] | 1 | 1 | 1 |
| 1 | [1, 2] | 2 | 1 | 2 |
| 2 | [1, 2, 1] | 2 | 2 | 3 |
| 3 | [1, 3] | 2 | 1 | 2 |
| 4 | [1, 3, 1] | 2 | 2 | 3 |
| 5 | [1, 2] | 2 | 1 | 2 |
| 6 | [1, 2, 2] | 2 | 2 | 3 |
| 7 | [2, 2, 4] | 2 | 2 | 3 |
The longest of these is 3.
Input: artists = [5, 5, 5, 5], k = 1, cap = 2
Output: 2One artist is allowed, but no artist may play more than twice, so the longest session is 2 tracks.
Input: artists = [7, 8, 9], k = 5, cap = 5
Output: 3Three different artists is within the limit of 5, so the whole history of 3 tracks is allowed.
1 ≤ len(artists) ≤ 100,0000 ≤ artists[i] ≤ 1,000,000,0001 ≤ k ≤ 100,0001 ≤ cap ≤ 100,000Checking every run of tracks means almost 5 billion runs, each with its own counts. That is too slow for a 2-second limit. Shrinking a run never breaks a limit. So a window that grows on the right and shrinks on the left finds the answer in one pass.