Taro Logo

Pairs of Songs With Total Durations Divisible by 60

Medium
Asked by:
Google
Amazon
Apple
TikTok
329 views
Topics:
Arrays

You are given a list of songs where the ith song has a duration of time[i] seconds.

Return the number of pairs of songs for which their total duration in seconds is divisible by 60. Formally, we want the number of indices i, j such that i < j with (time[i] + time[j]) % 60 == 0.

Example 1:

Input: time = [30,20,150,100,40]
Output: 3
Explanation: Three pairs have a total duration divisible by 60:
(time[0] = 30, time[2] = 150): total duration 180
(time[1] = 20, time[3] = 100): total duration 120
(time[1] = 20, time[4] = 40): total duration 60

Example 2:

Input: time = [60,60,60]
Output: 3
Explanation: All three pairs have a total duration of 120, which is divisible by 60.

Constraints:

  • 1 <= time.length <= 6 * 104
  • 1 <= time[i] <= 500

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the expected data type of the elements in the input list, and what are the minimum and maximum possible lengths of the array?
  2. Can the song durations include negative numbers, zero, or floating-point values, or are they strictly positive integers?
  3. How should we handle empty arrays or arrays with fewer than two elements—should the function return 0?
  4. The problem description mentions 'unique pairs' based on song positions; if an array has identical song durations at different indices, should each combination of indices be counted as a distinct valid pair?
  5. Is there a maximum upper bound for an individual song's duration, or could values exceed 60?

Brute Force Solution

Approach

Imagine you have a playlist of songs and you want to find every unique pair of songs whose combined length adds up to an exact multiple of sixty seconds. The brute force approach relies on checking every single possible pair of songs to see if their combined duration fits the rule.

Here's how the algorithm would work step-by-step:

  1. Begin by selecting the very first song in your playlist.
  2. Compare the length of this first song with the length of every other song that comes after it, one by one.
  3. For each pairing, add the two song lengths together to get a total combined duration.
  4. Check if this combined total can be divided evenly by sixty with nothing left over.
  5. If the total works out to a clean multiple of sixty, count that combination as a valid pair.
  6. Once you have checked the first song against all the remaining songs, move on to the second song.
  7. Repeat the exact same process of comparing this new song with all the songs that follow it.
  8. Continue this systematic checking for every single song in the playlist until every possible pair has been tested.
  9. Finally, count up all the valid pairs you found along the way to get your total result.

Code Implementation

def num_pairs_divisible_by_60(song_durations):
    total_valid_pairs = 0
    
    # Iterate through each song to establish it as the first element of our pairing
    for outer_index in range(len(song_durations)):
        
        # Compare against all subsequent songs to avoid duplicate pair evaluations
        for inner_index in range(outer_index + 1, len(song_durations)):
            combined_duration = song_durations[outer_index] + song_durations[inner_index]
            
            # Verify if the combined duration is an exact multiple of sixty seconds
            if combined_duration % 60 == 0:
                total_valid_pairs += 1
                
    return total_valid_pairs

Big(O) Analysis

Time Complexity
O(n²) – For each of n songs in the playlist, we systematically compare it against every other remaining song that follows it to check their combined duration. For the first song, we check n minus 1 subsequent songs, for the second song we check n minus 2, and so on until the final song. This nested pairing process results in approximately n times n divided by 2 total comparisons. Dropping constants and lower-order terms, this simplifies to a final time complexity of O(n²).
Space Complexity
O(1) – The optimal solution for this problem utilizes a fixed-size frequency array or hash map of size 60 to keep track of the remainders of song durations divided by 60. Because the number of possible remainders is strictly bounded by 60 regardless of how large the input playlist size N grows, the extra memory required remains constant. Therefore, the auxiliary space complexity simplifies to O(1) as it does not scale with the number of songs.

Optimal Solution

Approach

Instead of checking every possible pairing of songs, the optimal approach uses a clever counting strategy based on remainders. By figuring out what remainder is needed to make a multiple of sixty for each song, we can instantly find matching partners we have already seen.

Here's how the algorithm would work step-by-step:

  1. Imagine keeping a tally sheet with sixty slots, where each slot represents a possible remainder when a song duration is divided by sixty.
  2. Look at the duration of each song one by one as it comes up.
  3. Calculate what remainder is left over when the current song duration is divided by sixty.
  4. Figure out the complementary remainder needed so that when added to the current song, the total time divides evenly into sixty.
  5. Check your tally sheet to see how many previous songs had that exact complementary remainder.
  6. Add that number of previous songs to your overall count of successful pairs.
  7. Record the current song's remainder onto your tally sheet so future songs can potentially match with it.
  8. Continue this process for every song until you have checked them all, instantly knowing the total number of valid pairs without comparing every song to every other song.

Code Implementation

def num_pairs_divisible_by_sixty(song_durations):    valid_pair_count = 0    remainder_tally_sheet = [0] * 60    for current_duration in song_durations:        current_remainder = current_duration % 60                # We need the complementary remainder that sums with the current remainder to reach a multiple of sixty.        complementary_remainder = (60 - current_remainder) % 60        valid_pair_count += remainder_tally_sheet[complementary_remainder]        # Record the current song's remainder onto the tally sheet so future songs can match with it.        remainder_tally_sheet[current_remainder] += 1    return valid_pair_count

Big(O) Analysis

Time Complexity
O(n) – To find the valid pairs, we iterate through the list of n song durations exactly once, performing a constant time lookup and update in our tally sheet of sixty remainder slots for each song. Since we examine every song independently in a single pass without using nested loops, the number of operations scales linearly with the input size. This leads directly to approximately n operations, which simplifies to Big O of n.
Space Complexity
O(1) – The extra memory is driven entirely by a fixed-size tally sheet with sixty slots, as described in step one, to record remainders from zero to fifty-nine. Regardless of how many songs are in the input array denoted by N, this lookup structure never exceeds a constant size of sixty integers. Because the memory required does not grow with the input size N, the auxiliary space complexity simplifies to O(1) constant time.

Edge Cases

Empty array or array with only one element
How to Handle:
Return zero immediately since at least two elements are required to form a pair.
Durations that are exact multiples of 60
How to Handle:
Map lookups must use the remainder modulo 60, meaning a song of length 60 pairs with another song of length 60 because 0 plus 0 is divisible by 60.
Complement remainder is 0
How to Handle:
When the current song has a remainder of 0, we must look for previously seen songs with a remainder of 0 to form a valid sum divisible by 60.
Array containing all identical song durations
How to Handle:
The frequency array or hash map correctly accumulates counts so that every prior occurrence pairs with the current element.
Very large dataset with maximum constraints
How to Handle:
A single-pass frequency array approach runs in O(N) time complexity, efficiently scaling without exceeding time limits.
No valid pairs exist in the array
How to Handle:
The running count remains zero and the function correctly returns zero at the end of execution.
Integer overflow during pair counting
How to Handle:
Using a 64-bit integer for the total pair count prevents arithmetic overflow when the input size is maximal and all pairs are valid.
Durations greater than 60
How to Handle:
Taking the modulo 60 of each duration normalizes the values into the correct remainder bucket from 0 to 59.