Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: For n ≤ 2 × 10⁵ integers in the range −10⁴..10⁴, count subarrays with sum exactly k. Why does a two-pointer sliding window NOT work here, while prefix sums + hash map do?

  1. A. Sliding windows only work on sorted arrays
  2. B. With negative values, extending the window can decrease the sum, so shrinking/expanding decisions are not monotonic
  3. C. A hash map is needed because k can exceed 10⁴
  4. D. Sliding windows need O(n²) time for counting problems

Correct answer: B. With negative values, extending the window can decrease the sum, so shrinking/expanding decisions are not monotonic

A window works when adding an element always increases (or never decreases) the sum, so a too-large window can only be fixed by shrinking. Negatives break that monotonicity. Prefix sums with a count map handle any sign in O(n). Sorting is irrelevant (it destroys contiguity).

More Coding Interview Problems questions

Exams that ask this topic