Data Structures & AlgorithmsVery hardGATE CS · ICPC regional

How many contiguous subarrays of [3, -1, 2, -2, 4, -3, 1] have sum exactly 2?

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

Correct answer: B. 6

Prefix sums with a hash count: a subarray (i, j] sums to 2 when prefix[j] − 2 equals an earlier prefix; the total is 6. Forgetting the seeded prefix 0 gives 4, a two-pointer window (broken by negatives) finds 1, and looking up prefix + 2 counts sum −2 (2).

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

Exams that ask this topic