Data Structures & AlgorithmsVery hardProduct company OA

Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign follows the dividend). What is printed?

Count subarrays whose sum is divisible by 3 using prefix sums and a remainder map. The second version imitates C's % operator (sign follows the dividend). What is printed?
def div_count(a, k):
    seen = {0: 1}; s = c = 0
    for x in a:
        s = (s + x) % k
        c += seen.get(s, 0)
        seen[s] = seen.get(s, 0) + 1
    return c
def c_style(a, k):
    seen = {0: 1}; s = c = 0
    for x in a:
        s = s + x
        r = abs(s) % k * (1 if s >= 0 else -1)
        c += seen.get(r, 0)
        seen[r] = seen.get(r, 0) + 1
    return c
a = [4, -6, 2, -3, 5, 1]
print(div_count(a, 3), c_style(a, 3))
  1. A. 6 7
  2. B. 7 7
  3. C. 5 6
  4. D. 7 6

Correct answer: D. 7 6

Two prefixes with equal remainder bracket a subarray whose sum is a multiple of k. Prefix sums: 4, −2, 0, −3, 2, 3. Python's % maps them to 1, 1, 0, 0, 2, 0; with the initial 0 the classes are {0: 4, 1: 2, 2: 1} → C(4,2) + C(2,2) = 7. With C-style %, −2 gives −2 instead of 1, so the 4 and −2 prefixes land in different buckets and that pair is missed → 6. In C/C++/Java one must normalise ((s % k) + k) % k.

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

Exams that ask this topic