Data Structures & AlgorithmsModerateCodeforces Div2 B-D · ICPC regional

How many non-empty contiguous subarrays of [2, -1, -1, 3, -2, 1, 1, -2, 0] have a sum of exactly 0?

  1. A. 9
  2. B. 8
  3. C. 4
  4. D. 1

Correct answer: A. 9

Prefix sums 0, 2, 1, 0, 3, 1, 2, 3, 1, 1: value 1 occurs 4 times (6 pairs), and 0, 2, 3 twice each, so 6 + 1 + 1 + 1 = 9. Forgetting the initial prefix 0 gives 8; 4 counts the repeated prefix values, not pairs, and 1 counts only the single 0 element.

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

Exams that ask this topic