Pairs of Songs With Total Durations Divisible by 60 - Problem

You are given a list of songs where the i-th 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.

Input & Output

Example 1 — Basic Case
$ Input: time = [30,20,150,100,40]
Output: 3
💡 Note: Three pairs sum to multiples of 60: (30,150)=180, (20,40)=60, (100,40)=140. Wait, let me recalculate: (30,150)=180≡0, (20,40)=60≡0, (30,30) from positions would be invalid since we need i
Example 2 — Multiple Zeros
$ Input: time = [60,60,60]
Output: 3
💡 Note: All songs are 60 seconds (remainder 0). Every pair sums to 120≡0 (mod 60). Pairs: (0,1), (0,2), (1,2) = 3 pairs total.
Example 3 — No Valid Pairs
$ Input: time = [10,50,90,30]
Output: 2
💡 Note: Pairs that sum to multiples of 60: (10,50)=60 and (90,30)=120, so 2 pairs total.

Constraints

  • 1 ≤ time.length ≤ 6 × 104
  • 1 ≤ time[i] ≤ 500

Visualization

Tap to expand
Pairs of Songs Divisible by 60 INPUT time[] array 30 i=0 20 i=1 150 i=2 100 i=3 40 i=4 time[i] % 60: 30 20 30 40 40 Valid Pairs (sum % 60 == 0): (30, 150): 30+30=60 (20, 100): 20+40=60 (20, 40): 20+40=60 ALGORITHM STEPS 1 Create count[60] Track remainders 0-59 2 For each time[i] rem = time[i] % 60 3 Find complement comp = (60 - rem) % 60 4 Add + Update result += count[comp] count[rem]++ Count Array (key remainders): rem 20 cnt:1 rem 30 cnt:2 rem 40 cnt:2 O(n) time, O(1) space (count array fixed size 60) FINAL RESULT Number of valid pairs: 3 Pair Details: Pair 1: i=0,j=2: 30+150=180 OK Pair 2: i=1,j=3: 20+100=120 OK Pair 3: i=1,j=4: 20+40=60 OK All divisible by 60 Key Insight: Two numbers sum to a multiple of 60 if their remainders (mod 60) sum to 0 or 60. For remainder r, we need complement (60-r) % 60. Using a count array of size 60, we can find pairs in O(n) time by counting seen remainders before each element. TutorialsPoint - Pairs of Songs With Total Durations Divisible by 60 | Optimal Solution
Asked in
Amazon 15 Facebook 8
60.4K Views
Medium Frequency
~15 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen