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:
|
|
Example 2:
|
|
Constraints:
1 <= time.length <= 6 * 10^4
1 <= 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
remainder
for each song duration:remainder = time[i] % 60
. - Keep track of the count of each remainder using an array
freq
of 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 respectivefreq
index 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
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of songs (we iterate the list once). - 🧺 Space complexity:
O(60)
which reduces toO(1)
(fixed size array for remainders).