Data Structures & AlgorithmsHardTCS Digital · Infosys SP

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, -3, 2, -3, -3, 3, -3, 2, 1]
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. 6
  2. B. 7
  3. C. 5
  4. D. 4

Correct answer: C. 5

Each earlier prefix equal to the current one bounds a zero-sum subarray; seeding f[0] = 1 counts subarrays that start at index 0. Count: 5.

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

Exams that ask this topic