Data Structures & AlgorithmsHardTCS Digital · Infosys SP

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

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

Correct answer: A. 4

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 − 4] at every step. The total is 4. 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