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

Problem: Count subarrays whose sum is divisible by k (values may be negative).

Problem: Count subarrays whose sum is divisible by k (values may be negative).
def div_k(a, k):
    cnt = [0] * k
    cnt[0] = 1
    p = ans = 0
    for x in a:
        p = (p + x) % k
        ans += cnt[p]
        cnt[p] += 1
    return ans
print(div_k([4, 5, 0, -2, -3, 1], 5))
What is printed?
  1. A. 7
  2. B. 6
  3. C. 4
  4. D. 13

Correct answer: A. 7

Two prefixes with the same remainder bound a divisible subarray. Python's % keeps remainders in 0..k−1, so the prefix remainders are 0 (initial), 4, 4, 4, 2, 4, 0 and pairs = C(2,2) + C(4,2) = 1 + 6 = 7. Forgetting the initial cnt[0] = 1 gives 6, counting after incrementing gives 13, and C++/Java-style truncated remainders (negative buckets) give 4 unless you write ((p % k) + k) % k.

More Coding Interview Problems questions

Exams that ask this topic