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?
- A. The hash map sorts the prefix sums, which the window cannot do.
- B. A sliding window cannot store more than one number at a time.
- C. Negative numbers make every subarray sum equal to zero.
- 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.
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 counting pairs with a given sum in a sorted array using two pointers, why is sorting essential?
- The 3-sum two-pointer method skips a value when it equals the previous value. Why?
- What is the lexicographically smallest array of length n with positive integers and total sum S (S ≥ n)?
- In the 'minimum swaps to sort a permutation' problem, why is the answer n minus the number of cycles?
- Which statement about a monotonic deque for sliding-window minimum is correct?
- Why is prefix-sum counting of zero-sum subarrays unaffected by the choice of starting index for the prefix array?