Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA

Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code.

Problem: How many contiguous subarrays of [4, 1, -1, 2, 3] have a sum divisible by 4? Run the prefix-count code.
from collections import Counter
a = [4, 1, -1, 2, 3]
c = Counter({0: 1})
s = ans = 0
for x in a:
    s = (s + x) % 4
    ans += c[s]
    c[s] += 1
print(ans)
What is printed?
  1. A. 6
  2. B. 5
  3. C. 7
  4. D. 4

Correct answer: D. 4

Equal prefix residues mod 4 mark subarrays whose sum is divisible by 4, and the hash-map count of such pairs is 4.

More Coding Interview Problems questions

Exams that ask this topic