Pairs of Songs With Total Durations Divisible by 60

Count pairs `(i, j)` with `(t[i] + t[j]) % 60 == 0` — residue bucketing.

Medium
Time O(N) Space O(1)
LeetCode
3 min read
hash-map counting modular

Problem#

Given integer durations time, count pairs of indices (i, j) with i < j and (time[i] + time[j]) % 60 == 0.

Examples#

  • [30,20,150,100,40]3.
  • [60,60,60]3.

Constraints#

  • 1 <= time.length <= 6 * 10^4, 1 <= time[i] <= 500.

Hints#

Hint
For each song, its complement residue is (60 - t % 60) % 60.

Approach#

Single pass with cnt[60]. For each t, add cnt[(60 - t % 60) % 60] to the answer, then increment cnt[t % 60]. The double-mod handles t % 60 == 0 correctly (complement is 0, not 60).

Solution#

Pairs of Songs With Total Durations Divisible by 60
class Solution {
public:
int numPairsDivisibleBy60(vector<int>& time) {
int cnt[60] = {0};
long long ans = 0;
for (int t : time) {
int r = t % 60;
ans += cnt[(60 - r) % 60];
++cnt[r];
}
return static_cast<int>(ans);
}
};

Editorial#

Bucketing by residue mod 60 turns the pair-sum-divisible question into a classic Two Sum mod variant. Incrementing the counter after lookup ensures we only count pairs with i < j. The (60 - r) % 60 handles the zero-residue case cleanly.

Complexity#

  • Time: O(N).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.