Pairs of Songs With Total Durations Divisible by 60
MediumUpdated: Aug 2, 2025
Practice on:
Problem
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.
Examples
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
Method 1 - Using Hashtable
The problem requires efficiently finding pairs of song durations that sum up to a multiple of 60. A direct approach using nested loops would lead to O(n^2) complexity, which is computationally expensive for large input sizes. Instead, we use a modulo-based approach with a hash map to store the frequency of remainders modulo 60, reducing the complexity to linear time.
Steps:
- Calculate
remainderfor each song duration:remainder = time[i] % 60. - Keep track of the count of each remainder using an array
freqof size60. - For each song duration:
- Determine the complement remainder that pairs to form a sum divisible by
60. The complement is(60 - remainder) % 60. - Add the count of complement remainder to the answer (
ans), then increment the respectivefreqindex for the current duration's remainder.
- Determine the complement remainder that pairs to form a sum divisible by
- Return the total count.
Edge cases
- If the remainder is
0, the complement is also0.
Code
Java
class Solution {
public int numPairsDivisibleBy60(int[] time) {
int[] freq = new int[60];
int ans = 0;
for (int t : time) {
int rem = t % 60;
int complement = (60 - rem) % 60;
ans += freq[complement];
freq[rem]++;
}
return ans;
}
}
Python
class Solution:
def numPairsDivisibleBy60(self, time: List[int]) -> int:
freq = [0] * 60
ans = 0
for t in time:
rem = t % 60
complement = (60 - rem) % 60
ans += freq[complement]
freq[rem] += 1
return ans
Complexity
- ⏰ Time complexity:
O(n)wherenis the number of songs (we iterate the list once). - 🧺 Space complexity:
O(60)which reduces toO(1)(fixed size array for remainders).