Pairs of Songs With Total Durations Divisible by 60 — LeetCode 1010 Python Solution

MediumArrayHash TableCounting
Problem
#1010
Pattern
Hash Map
Reading time
2 min

The problem

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.

Example

Input
time = [30,20,150,100,40]
Output
3
Explanation
Three pairs have a total duration divisible by 60:

Python solution

Python
class Solution:
    def numPairsDivisibleBy60(self, time: List[int]) -> int:
        cnt = Counter(t % 60 for t in time)
        ans = sum(cnt[x] * cnt[60 - x] for x in range(1, 30))
        ans += cnt[0] * (cnt[0] - 1) // 2
        ans += cnt[30] * (cnt[30] - 1) // 2
        return ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60 is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Hash Table and Counting.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60?
LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60 is rated Medium on LeetCode.
What is the time complexity of LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60 cover?
LeetCode 1010. Pairs of Songs With Total Durations Divisible by 60 is tagged Array, Hash Table and Counting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview