Music streaming app~20 min2s · 256 MBtarget O(n) time, O(slot) spaceclassic twin: lc-1010, lc-1hashing
A music streaming app builds radio-style channels. The channel clock runs in slots of slot seconds. Two tracks can be played back to back as one block when their lengths add up to a whole number of slots.
The scheduler wants to know how many different pairs of tracks in a catalogue section can form such a block.
Write count_slot_pairs(durations, slot).
durations[i] is the length of the i-th track in seconds.i < j is a block when durations[i] + durations[j] is a multiple of slot.Input: durations = [45, 15, 75, 120, 30, 90, 60], slot = 60
Output: 4Only the remainder after dividing by 60 matters. A track with remainder r needs a partner with remainder (60 - r) mod 60.
| Position | Length | Remainder | Partner remainder | Earlier tracks with it | Pairs so far |
|---|---|---|---|---|---|
| 0 | 45 | 45 | 15 | 0 | 0 |
| 1 | 15 | 15 | 45 | 1 | 1 |
| 2 | 75 | 15 | 45 | 1 | 2 |
| 3 | 120 | 0 | 0 | 0 | 2 |
| 4 | 30 | 30 | 30 | 0 | 2 |
| 5 | 90 | 30 | 30 | 1 | 3 |
| 6 | 60 | 0 | 0 | 1 | 4 |
The blocks are positions (0, 1), (0, 2), (4, 5) and (3, 6).
Input: durations = [10, 20, 30], slot = 7
Output: 0The totals are 30, 40 and 50. None is a multiple of 7.
Input: durations = [60, 60, 60], slot = 60
Output: 3Every track is a whole slot. Any two of the three make a block: 3 pairs.
1 ≤ durations.length ≤ 100,000 (tracks in a catalogue section)1 ≤ durations[i] ≤ 10^6 (seconds)1 ≤ slot ≤ 10^6Testing every pair costs about n × n / 2 checks, which is about 5 × 10^9 at n = 100,000. A map from remainder to count answers each track in one step, so one pass makes about n steps.
Read the answer too. With 100,000 tracks there can be about 5 × 10^9 pairs, more than a 32-bit int can hold, so the result type is long.