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?- A. 2 3
- B. 3 3
- C. 3 1
- 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
- Problem: Find the length of the longest subarray with equal numbers of 0s and 1s. python def longesteq(a): first = {0: -1}; bal = best = 0…
- Problem: Find all elements that appear more than ⌊n/3⌋ times. python def overthird(a): c1 = c2 = None; n1 = n2 = 0 for x in a: if x == c1…
- Problem: Find the length of the shortest unsorted continuous subarray which, if sorted, makes the whole array sorted. python def…
- Problem: Compute the amount of rain water trapped between bars. python def trap(h): l, r = 0, len(h) - 1; lm = rm = water = 0 while l < r…
- Problem: Find the three numbers in an array whose sum is closest to a target. python def closest3(a, t): a.sort(); best = a[0] + a[1] +…
- Problem: Return all unique triplets that sum to zero. python def threesum(a): a.sort(); res = [] for i in range(len(a) - 2): if i and a[i]…