Data Structures & AlgorithmsHardProduct Company SDE · prefix-sum OA

Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code.

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

Correct answer: B. 6

Prefix sums are 0,1,0,2,0,3,0, and the value 0 appears four times, giving C(4,2) = 6 zero-sum subarrays. Counting only the adjacent cancelling pairs gives the trap 3.

More Coding Interview Problems questions

Exams that ask this topic