Data Structures & AlgorithmsHardProduct Company SDE · CP practice

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

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

Correct answer: C. 6

Prefix sums 0, 1, 0, 1, 0, 1 hold 0 three times and 1 three times, so C(3,2) + C(3,2) = 6. Not seeding the Counter with {0: 1} gives 4, counting only prefix value 0 gives 3, and 15 is all subarrays.

More Coding Interview Problems questions

Exams that ask this topic