GATE Computer ScienceVery hardGATE CS (PYQ pattern)

How many non-empty contiguous subarrays of [3, 4, −7, 1, 3, 3, 1, −4, 2, 5, −3, 6] have sum exactly 7?

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

Correct answer: B. 9

Using prefix sums P and a hash map of counts, add count[P[j] − 7] at each j. The prefix sums 0, 3, 7, 0, 1, 4, 7, 8, 4, 6, 11, 8, 14 give 9 pairs (i < j) with P[j] − P[i] = 7 (verified by direct enumeration).

More Algorithms questions

Exams that ask this topic