Pairs of Songs With Total Durations Divisible by 60 Problem
Description
LeetCode Problem 1010.
You are given a list of songs where the i^th song has a duration of time[i] seconds.
Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.
Example 1:
Input: time = [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60
Example 2:
Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.
Constraints:
1 <= time.length <= 6 * 10^41 <= time[i] <= 500
Solution
Approach: Count Remainders
Whether a + b is divisible by 60 only depends on the remainders a % 60 and b % 60: they must add up to 0 or 60. So a song with remainder r pairs with every song whose remainder is (60 - r) % 60. The outer % 60 handles r = 0, whose partner remainder is 0 and not 60 (two songs of 60 seconds make a pair).
Walk through the songs once, keeping cnt[r] = the number of songs seen so far with remainder r. For each song, first add cnt[(60 - r) % 60] to the answer (all earlier songs it pairs with), then count the song itself. Looking up before counting makes sure a song is never paired with itself, which matters for remainders 0 and 30, where a song is its own partner remainder.
The answer fits in a 32-bit integer: at most 60000 · 59999 / 2 ≈ 1.8 · 109.
Complexity: O(n) time and O(1) extra space (60 counters).
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
cnt = [0] * 60 # cnt[r] = songs seen so far with duration % 60 == r
pairs = 0
for t in time:
r = t % 60
pairs += cnt[(60 - r) % 60] # earlier songs that complete this one to a multiple of 60
cnt[r] += 1
return pairs