Data Structures & AlgorithmsHardGATE CS · DSA

How many contiguous subarrays of [3, 2, −3, 5, 2, −1, 0, 1, 2] have sum exactly 3? (Prefix sums with a hash map of prefix-sum frequencies.)

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

Correct answer: C. 5

Walk the array keeping prefix sum P and a map of how often each earlier prefix occurred (with P = 0 seeded once); add freq[P − 3] at every step. The total is 5. Forgetting the seeded 0 misses subarrays that start at index 0.

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

Exams that ask this topic