Pairs of Songs With Total Durations Divisible by 60

medium hash map counting modular arithmetic

Problem

You are given a list of song durations time in seconds. Return the number of pairs of songs (i, j) with i < j such that their total duration is divisible by 60, i.e. (time[i] + time[j]) % 60 == 0.

Inputtime = [30, 20, 150, 100, 40]
Output3
Pairs: (30, 150), (20, 100), (20, 40) — remainders 30+30, 20+40, 20+40 all sum to a multiple of 60.

def num_pairs_divisible_by_60(time):
    count = [0] * 60
    pairs = 0
    for t in time:
        r = t % 60
        need = (60 - r) % 60
        pairs += count[need]
        count[r] += 1
    return pairs
function numPairsDivisibleBy60(time) {
  const count = new Array(60).fill(0);
  let pairs = 0;
  for (const t of time) {
    const r = t % 60;
    const need = (60 - r) % 60;
    pairs += count[need];
    count[r] += 1;
  }
  return pairs;
}
class Solution {
    public int numPairsDivisibleBy60(int[] time) {
        int[] count = new int[60];
        int pairs = 0;
        for (int t : time) {
            int r = t % 60;
            int need = (60 - r) % 60;
            pairs += count[need];
            count[r]++;
        }
        return pairs;
    }
}
int numPairsDivisibleBy60(vector<int>& time) {
    vector<int> count(60, 0);
    int pairs = 0;
    for (int t : time) {
        int r = t % 60;
        int need = (60 - r) % 60;
        pairs += count[need];
        count[r]++;
    }
    return pairs;
}
Time: O(n) Space: O(1)