Problem Description
Given an array of song durations (in seconds), determine the number of pairs of songs (i, j with i < j) such that the sum of their durations is divisible by 60.
Key Insights
- Each song duration's effect is determined by its remainder when divided by 60.
- For any given module value r (where 0 ≤ r < 60), the complementary module needed to complete 60 is (60 - r) % 60.
- Special handling is needed when r is 0 (or 30, since 30 + 30 = 60) to avoid double-counting.
- A frequency counter for remainders can be efficiently used to count valid pairs in one pass through the list.
Space and Time Complexity
Time Complexity: O(n), where n is the number of songs. Space Complexity: O(60) → O(1), since we only need to keep track of 60 possible remainders.
Solution
We iterate over the list of song durations and calculate the remainder of each duration modulo 60. A frequency array (or hash table) is used to record how many times each remainder has been seen so far. For each song, we look up the frequency of its complementary remainder (i.e., (60 - current_remainder) % 60) already encountered. This frequency indicates how many valid pairs can be formed with the current song. After counting pairs with the current song, we update the frequency of its remainder for future pairings.