Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA

Problem: Count subarrays whose sum is divisible by k=5 for a = [4, 5, 0, -2, -3, 1].

Problem: Count subarrays whose sum is divisible by k=5 for a = [4, 5, 0, -2, -3, 1].
from collections import Counter
def f(a, k):
    c = Counter({0: 1})
    s = 0
    ans = 0
    for x in a:
        s = (s + x) % k
        ans += c[s]
        c[s] += 1
    return ans
print(f([4, 5, 0, -2, -3, 1], 5))
What is printed?
  1. A. 7
  2. B. 4
  3. C. 9
  4. D. 11

Correct answer: A. 7

Subarrays with equal prefix remainders have sums divisible by k. Python's % gives non-negative remainders for negative numbers here, which is why the code is correct.

More Coding Interview Problems questions

Exams that ask this topic