Data Structures & AlgorithmsHardGATE CS · DSA

Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed?

Count zero-sum contiguous subarrays with a prefix-sum frequency map. What is printed?
from collections import defaultdict
a = [1, -2, -1, 2, -3, 2, 0, 3, -2]
f, p, cnt = defaultdict(int), 0, 0
f[0] = 1
for x in a:
    p += x; cnt += f[p]; f[p] += 1
print(cnt)
  1. A. 1
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: C. 6

Prefix sums 0, 1, −1, −2, 0, −3, −1, −1, 2, 0: value 0 occurs 3 times and −1 occurs 3 times, so C(3,2) + C(3,2) = 6. Without the seed f[0] = 1 only 4 are found; pairing the zeros alone gives 3, and 1 counts just the single 0 element.

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

Exams that ask this topic