Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count pairs of songs whose total duration is divisible by 60.

Problem: Count pairs of songs whose total duration is divisible by 60.
def pairs60(t):
    cnt = [0] * 60; res = 0
    for x in t:
        r = x % 60
        res += cnt[(60 - r) % 60]
        cnt[r] += 1
    return res
print(pairs60([30, 20, 150, 100, 40]), pairs60([60, 60, 60]))
What is printed?
  1. A. 2 3
  2. B. 3 3
  3. C. 3 1
  4. D. 4 3

Correct answer: B. 3 3

Pair each remainder r with earlier songs of remainder (60 − r) mod 60 – the extra % 60 maps r = 0 to bucket 0 rather than 60. (30,150), (20,100), (20,40) → 3; three multiples of 60 form C(3,2) = 3 pairs. O(n).

More Coding Interview Problems questions

Exams that ask this topic