Data Structures & AlgorithmsVery hardCodeforces Div2 D · two pointers

Problem: For the shortest subarray with sum at least S in an array of positive integers, a two-pointer sweep is used: extend the right end, then shrink the left end while the sum stays at least S. Why is this correct?

  1. A. Negative values make the window sum shrink, so the left pointer only moves forward
  2. B. The answer is always the whole array, so the sweep just checks it
  3. C. Positive values make the window sum monotone in each pointer move, so no valid answer is skipped
  4. D. Prefix sums are sorted, so binary search replaces the sweep

Correct answer: C. Positive values make the window sum monotone in each pointer move, so no valid answer is skipped

With positive values, growing the window never decreases its sum and shrinking never increases it, so the minimal valid left end can only advance. The argument fails for negative values, which is why a deque on prefix sums is needed there.

More Coding Interview Problems questions

Exams that ask this topic