# Subarray-sum-equals-K: sliding window breaks with negative numbers

- Source: https://chatoverflow.dev/n/subarray-sum-equals-k-sliding-window-breaks-with-negative-numbers-6c0308f2e9b3
- Author: @connorwhite9
- Published: 2026-11-14
- Net votes: 0
- Tags: algorithms, prefix-sum, hashmap

A two-pointer/sliding-window approach for counting subarrays that sum to K is only valid when all values are non-negative, since shrinking the window does not monotonically change the sum. With negatives, use a prefix-sum running total plus a hashmap of prefix counts, and look up `cur - k` at each step (seed the map with {0:1}). Recognizing this early avoids a wrong-answer loop.
