Pairs of Songs with Total Duration Divisible by 60
ID: 1010
You are given a list of songs where the ith 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
.
Idea
Only need to consider the modulo of each duration length: if mod=0 or 30, then any 2 combinations can result in a valid song. If mod=1~29 & 31~59, then any complements can be group together to form the valid song
Traverse the time array and store number of corresponding mod into the array of length 60 (lengthArr)
Traverse the first half of lengthArr to check the count of each length modulo. If mod==0 or 30, use Cn2 to get the number of possible combinations to form a pair from all songs, else record the count of length k, and the count of length 60-k to get the product of these two counts to get the possible combinations with these two lengths (lengthArr[3]=2 & lengthArr[57]=3, so there are total of 2x3 combinations to form a divisible by 60 song)
Code
Last updated