Pairs of Songs With Total Durations Divisible by 60
Count pairs `(i, j)` with `(t[i] + t[j]) % 60 == 0` — residue bucketing.
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#
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); }};func numPairsDivisibleBy60(time []int) int { var cnt [60]int ans := 0 for _, t := range time { r := t % 60 ans += cnt[(60-r)%60] cnt[r]++ } return ans}from typing import List
class Solution: def numPairsDivisibleBy60(self, time: List[int]) -> int: cnt = [0] * 60 ans = 0 for t in time: r = t % 60 ans += cnt[(60 - r) % 60] cnt[r] += 1 return ansfunction numPairsDivisibleBy60(time) { const cnt = new Array(60).fill(0); let ans = 0; for (const t of time) { const r = t % 60; ans += cnt[(60 - r) % 60]; cnt[r]++; } return ans;}class Solution { public int numPairsDivisibleBy60(int[] time) { int[] cnt = new int[60]; long ans = 0; for (int t : time) { int r = t % 60; ans += cnt[(60 - r) % 60]; cnt[r]++; } return (int) ans; }}function numPairsDivisibleBy60(time: number[]): number { const cnt: number[] = new Array(60).fill(0); let ans = 0; for (const t of time) { const r = t % 60; ans += cnt[(60 - r) % 60]; cnt[r]++; } return 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#
Related#