Data Structures & AlgorithmsHardCodeforces Div 2 C · ICPC regional

Array a = [1, -1, 2, 3, -2, 4, -3, 1]. How many contiguous non-empty subarrays have sum exactly 3? Solve it with running prefix sums and a hash map counting how often each prefix value has been seen.

  1. A. 5
  2. B. 4
  3. C. 6
  4. D. 3

Correct answer: A. 5

Count pairs of prefixes (i < j) with prefix[j] - prefix[i] = 3. Leaving out the empty prefix 0 from the map drops every subarray that starts at index 0, giving 4 instead of 5.

More Coding Interview Problems questions

Exams that ask this topic