Data Structures & AlgorithmsHard

Why does counting subarrays with sum exactly k, when elements can be NEGATIVE, use a hash map of prefix sums and not a sliding window?

  1. A. The hash map sorts the prefix sums, which the window cannot do.
  2. B. A sliding window cannot store more than one number at a time.
  3. C. Negative numbers make every subarray sum equal to zero.
  4. D. Negative values break the monotonicity of window sums, so shrinking the window does not reliably move the sum toward k.

Correct answer: D. Negative values break the monotonicity of window sums, so shrinking the window does not reliably move the sum toward k.

For positive numbers the window sum grows monotonically, but negatives make it jump both ways, so one pointer cannot decide when to move. Prefix sums turn the question into counting earlier equal values.

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

Exams that ask this topic