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.
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 * 1041 <= time[i] <= 500This approach uses the idea of complementary remainders. If the sum of the remainders of two numbers when divided by 60 equals 60, then their sum is divisible by 60. For example, if the remainder of a number A is 10, you would need a number B whose remainder is 50 to ensure their sum is divisible by 60 (since 10 + 50 = 60).
We can leverage this by keeping a count of all remainders encountered so far and for each number, check for its complement remainder that, when added, will result in a number divisible by 60.
The C solution uses an array 'remainder' to store counts of remainders of each number in the input divided by 60. For each element, it checks how many elements with a complementary remainder have been seen so far and adds that count to the total.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N), where N is the number of songs.
Space Complexity: O(1), since we use a fixed-size array of size 60.
In this approach, we use a brute force double loop to compare each pair of songs. For each song, pair it with every other song that comes after it and check if their total duration is divisible by 60. This is a straightforward method but inefficient for large inputs.
Although simple, this method is not optimal for large datasets but can work if constraints are smaller.
The brute force C solution uses nested loops to compute every possible pair of songs and checks if their combined duration is divisible by 60. This results in a simple, albeit inefficient solution.
C++
Java
Python
C#
JavaScript
Time Complexity: O(N^2), iterating over every possible pair.
Space Complexity: O(1), with no additional space used apart from the input array.
| Approach | Complexity |
|---|---|
| Using Complementary Remainders | Time Complexity: O(N), where N is the number of songs. |
| Brute Force Approach | Time Complexity: O(N^2), iterating over every possible pair. |
Pairs of songs with total durations divisible by 60 | Leetcode #1010 • Techdose • 26,108 views views
Watch 9 more video solutions →Practice Pairs of Songs With Total Durations Divisible by 60 with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor