Data Structures & AlgorithmsHardCodeforces Div2 C · TCS NQT

How many contiguous subarrays of [3, 4, -7, 1, 3, 3, 1, -4, 2] have sum exactly 7? Negative numbers are present.

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

Correct answer: D. 4

Keep a map of prefix sums seen so far (starting with 0 : 1) and add the number of earlier prefixes equal to current − k. A sliding window that shrinks on overshoot fails with negative values, so the map is the right tool here.

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

Exams that ask this topic