Pairs of Songs With Total Durations Divisible by 60
You're given a list of song lengths in seconds, time. Return how many pairs of songs have a total length that's divisible by 60. A pair is two different songs at indexes i < j.
Example 1
Input: time = [30, 20, 150, 100, 40] Output: 3
The pairs are 30 + 150 = 180, 20 + 100 = 120 and 20 + 40 = 60.
Example 2
Input: time = [60, 60, 60] Output: 3
Every pair adds up to 120, and three songs make three pairs.
Constraints
1 <= time.length <= 600001 <= time[i] <= 500
Approach
Checking every pair takes O(n²) time. But only the remainder of each length after dividing by 60 matters: two songs add up to a multiple of 60 exactly when their remainders add up to 60, or when both remainders are 0.
So walk through the songs once and count remainders as you go. For a song with remainder r, every earlier song with remainder (60 - r) % 60 forms a valid pair, so add that count to the answer before recording the current song. The % 60 handles remainder 0, which pairs with itself. Remainder 30 pairs with itself too, and counting only earlier songs means no pair is counted twice.
Steps
- Create an array of 60 zeros for remainder counts and set
pairsto0. - For each length
t, computer = t % 60. - Add
remainders[(60 - r) % 60]topairs. - Increase
remainders[r]by 1. Returnpairsat the end.
from typing import List
def num_pairs_divisible_by_60(time: List[int]) -> int:
remainders = [0] * 60 # remainders[r] counts earlier songs whose length leaves remainder r
pairs = 0
for t in time:
r = t % 60
pairs += remainders[(60 - r) % 60] # earlier songs that complete this one to a multiple of 60
remainders[r] += 1
return pairsComplexity
- Time:
O(n). Each song does constant work. - Space:
O(1). The array always has 60 slots.
Common mistakes
- Looking up
60 - rwithout the final% 60. A remainder of 0 then looks for remainder 60, which never exists. - Recording the current song before counting its partners. With remainders 0 or 30, the song pairs with itself.
- Counting both orders of each pair. Only looking at earlier songs counts each pair once.