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?
- A. Right ends are processed in sorted order of their sums.
- B. Adding an element on the right can only increase the window sum, so a left end that was invalid stays invalid.
- C. The right pointer is reset to the left pointer after each shrink.
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- When summing the MAXIMUM over all subarrays with repeated values, the standard contribution method uses one strict and one non-strict…
- Which statement about subarrays with XOR equal to 0 is CORRECT?
- A zero-sum subarray counter keeps a map of prefix sums. At each index the current prefix is inserted into the map BEFORE the lookup. What…
- For pairs i < j with (ai + aj) divisible by an EVEN number m, with remainder counts cr, which formula is correct?
- Which statement about counting subarrays with EXACTLY k distinct values is correct?
- Positive integers, two pointers count subarrays with product less than K. Why is right − left + 1 added for each right end?