Data Structures & AlgorithmsHardProduct placement · Amazon/Microsoft

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

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

Correct answer: A. 6

Walk the array keeping prefix sum P and a map of earlier prefixes (with P = 0 seeded once); add freq[P − 5] at every step: total 6. Forgetting the seed gives 5, a two-pointer window (invalid with negatives) finds 2, and counting only prefixes equal to 5 finds 1.

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

Exams that ask this topic