Track pairs by remainder

Write codeMedium16 min

Your task

A DJ tool suggests smooth crossfades between tracks whose combined duration lines up with a beat grid. Given a list of track durations in seconds and a grid length k (k >= 1), count the pairs of indices i < j such that durations[i] + durations[j] is divisible by k. For example, with durations [30, 20, 150, 100, 40] and k = 60, the qualifying pairs are (30, 150), (20, 100) and (20, 40), so the answer is 3. Checking every pair is O(n^2), count by remainder instead.

Examples

divisible_pairs(durations: list[int], k: int) -> int
Example 1
Inputdivisible_pairs([30, 20, 150, 100, 40], 60)
Output3