Music streaming app~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-3, lc-1695sliding-window-variable · hashing
A music streaming app's recommendations team studies how listeners discover music. One measure they like is a fresh session: plays in a row where no track repeats. A long fresh session suggests that the recommendations kept finding new music the listener enjoyed.
For each listener, the team takes the listening history in order and asks for the length of the longest fresh session. Track ids are large numbers from the catalogue. A brand-new account may have no plays yet.
Write longest_fresh(tracks).
tracks[i] is the id of the track played at position i of the history, in order.0.Input: tracks = [5, 8, 5, 3, 8, 2]
Output: 4| right | Track | Last seen at | left after the step | Session | Length | Best |
|---|---|---|---|---|---|---|
| 0 | 5 | never | 0 | 5 | 1 | 1 |
| 1 | 8 | never | 0 | 5, 8 | 2 | 2 |
| 2 | 5 | 0 | 1 | 8, 5 | 2 | 2 |
| 3 | 3 | never | 1 | 8, 5, 3 | 3 | 3 |
| 4 | 8 | 1 | 2 | 5, 3, 8 | 3 | 3 |
| 5 | 2 | never | 2 | 5, 3, 8, 2 | 4 | 4 |
When track 5 plays again at position 2, the session must start after its earlier play, at position 1.
Input: tracks = [4, 4, 4]
Output: 1The same track on repeat: every fresh session is one play long.
Input: tracks = []
Output: 0A new account with no plays has no session.
0 ≤ tracks.length ≤ 10^51 ≤ tracks[i] ≤ 10^9Checking every start and extending until a repeat is O(n^2) in the worst case: about 5 × 10^9 steps when there are few repeats. Aim for O(n).
The ids go up to 10^9, so you cannot use an array indexed by track id. Use a hash map from track id to the position where it was last played.