Data Structures & AlgorithmsVery hardProduct Company SDE · ICPC regional

Count the non-empty subarrays of a = [3, -1, 4, -1, 5, -9, 2, 6] whose sum is divisible by 5, using prefix sums taken modulo 5.

Count the non-empty subarrays of a = [3, -1, 4, -1, 5, -9, 2, 6] whose sum is divisible by 5, using prefix sums taken modulo 5.
a=[3,-1,4,-1,5,-9,2,6]
c={0:1}; s=0; ans=0
for x in a:
    s=(s+x)%5
    ans+=c.get(s,0); c[s]=c.get(s,0)+1
print(ans)
What is printed?
  1. A. 5
  2. B. 3
  3. C. 1
  4. D. 2

Correct answer: A. 5

Equal prefix residues mod 5 mark a subarray whose sum is divisible by 5; the map must start with residue 0 for the empty prefix. Using raw prefix sums counts zero-sum subarrays instead, and checking only prefixes from index 0 misses most subarrays.

More Coding Interview Problems questions

Exams that ask this topic