Data Structures & AlgorithmsHardFlipkart/Uber OA · placement

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 = [0, 3, 0, 2, -1, 1, 2, 3, -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. 4
  2. B. 5
  3. C. 3
  4. D. 2

Correct answer: C. 3

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: 3.

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

Exams that ask this topic