Data Structures & AlgorithmsHardCodeforces Div2 B-D · ICPC regional

An array of 200000 integers may contain negative values, and you must count its contiguous subarrays whose sum equals K in near-linear time. Which technique fits, and why?

  1. A. Prefix sums with a hashmap counting earlier equal prefixes, because two-pointer windows need monotone sums and negatives break that
  2. B. Sliding window with two pointers, because every sum window can be shrunk greedily
  3. C. Binary search on the answer, because the sum is monotone in the subarray length
  4. D. Monotonic stack, because each element is the maximum of its subarray

Correct answer: A. Prefix sums with a hashmap counting earlier equal prefixes, because two-pointer windows need monotone sums and negatives break that

Negative values make the window sum non-monotone in the right end, so the usual shrink rule fails. Prefix sums turn each subarray into a difference of two prefixes, which a hashmap counts in O(n).

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

Exams that ask this topic