Data Structures & AlgorithmsHard

Two pointers count subarrays of POSITIVE integers with sum at most K. Why can the left pointer only move forward as the right pointer moves?

  1. A. Right ends are processed in sorted order of their sums.
  2. B. Adding an element on the right can only increase the window sum, so a left end that was invalid stays invalid.
  3. C. The right pointer is reset to the left pointer after each shrink.
  4. D. Subarray sums are sorted whenever the array is positive.

Correct answer: B. Adding an element on the right can only increase the window sum, so a left end that was invalid stays invalid.

Positive values make the window sum non-decreasing when the right end grows, so an invalid left end never becomes valid again. That monotonicity is what allows a single forward sweep of the left pointer.

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

Exams that ask this topic