Music streaming app~20 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-2006hashing
You work on a music streaming service. A log holds the play count of each track, in the order the tracks were added. The recommendations team wants pairs of tracks whose play counts are exactly one band apart.
Your team lead asks: "How many pairs of tracks have play counts that differ by exactly gap?" The log can hold 100,000 tracks.
Write count_pairs_with_gap(plays, gap).
plays[i] is the play count of track i. Play counts can repeat.i < j with |plays[i] - plays[j]| = gap.gap is 0.0 when there is none.Input: plays = [1, 5, 3, 4, 2], gap = 2
Output: 3Read the plays from left to right. Before a play is recorded, count the earlier plays that equal play - 2 or play + 2.
| Play | Earlier matches | Total pairs |
|---|---|---|
| 1 | 0 | 0 |
| 5 | 0 | 0 |
| 3 | 2 | 2 |
| 4 | 0 | 2 |
| 2 | 1 | 3 |
The pairs are (1, 3), (3, 5) and (4, 2), counting by value.
Input: plays = [3, 3, 3], gap = 0
Output: 3A gap of 0 asks for equal plays. Three equal plays make 3 pairs.
Input: plays = [1, 100], gap = 5
Output: 0The two plays differ by 99, not by 5.
1 ≤ len(plays) ≤ 100,0001 ≤ plays[i] ≤ 1,000,000,0000 ≤ gap ≤ 1,000,000,000Comparing every pair takes n × (n - 1) / 2 comparisons: 4,999,950,000 for 100,000 plays. That is too slow for a 2-second limit. You need a way to find the partners of a play in about constant time, and a hash map does that.