Leetcode 1010: Pairs of Songs With Total Durations Divisible by 60

grid47
grid47
Exploring patterns and algorithms
Jul 29, 2024 5 min read

You are given an array where each element represents the duration of a song in seconds. Your task is to count how many pairs of songs have a total duration that is divisible by 60. Specifically, you need to count how many pairs of songs, indexed as i and j (with i < j), satisfy the condition (time[i] + time[j]) % 60 == 0.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers where each integer represents the duration of a song in seconds.
Example: time = [10, 50, 120, 80, 40]
Constraints:
• 1 <= time.length <= 6 * 10^4
• 1 <= time[i] <= 500
Output: The output should be the total number of valid pairs where the sum of the song durations is divisible by 60.
Example: Output: 2
Constraints:
• The result should be an integer representing the number of valid pairs.
Goal: The goal is to efficiently count the pairs of songs whose combined durations are divisible by 60.
Steps:
• For each song, find the remainder when the song's duration is divided by 60.
• Count how many other songs, when paired with the current song, have a remainder that completes the sum to be divisible by 60.
• Maintain a count of song durations modulo 60 to avoid recalculating the remainder each time.
Goal: Ensure that the solution can handle large inputs efficiently and correctly.
Steps:
• The input list can contain up to 6 * 10^4 song durations, so the solution should have an optimized time complexity.
Assumptions:
• Each song duration is unique, and all are between 1 and 500 seconds.
Input: Input: time = [10, 50, 120, 80, 40]
Explanation: In this case, two pairs of songs have durations that add up to a multiple of 60: (time[0] = 10, time[1] = 50) and (time[2] = 120, time[4] = 40). These pairs add up to 60 and 160, respectively, both of which are divisible by 60.

Input: Input: time = [60, 60, 60]
Explanation: For this input, all three pairs (time[0] = 60, time[1] = 60), (time[0] = 60, time[2] = 60), and (time[1] = 60, time[2] = 60) add up to 120, which is divisible by 60. Therefore, the output is 3.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus