Data Structures & AlgorithmsVery hardCodeforces Div2 C · TCS NQT

A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum.

A routine computes the number of subarrays whose sum is divisible by 5, using the remainder of each prefix sum.
a = [3, -1, 4, -6, 2, 1]
pre = [0]
for x in a: pre.append(pre[-1] + x)
cnt = {}
ans = 0
for s in pre:
    r = s % 5
    ans += cnt.get(r, 0)
    cnt[r] = cnt.get(r, 0) + 1
print(ans)
What is printed?
  1. A. 2
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: D. 3

Python's % always returns a remainder in [0, 5), so equal remainders mean the difference is divisible by 5. Mapping the remainder through abs (as C/Java would with a sign-preserving %) splits equal residues into different buckets and undercounts.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic