Skip to content
Preptima
mediumCodingConceptMidSenior

Count the subarrays whose elements sum to k, where the values may be negative.

Subarray Sum Equals K is solved with prefix sums and a hash map: for each running sum, count earlier prefixes equal to sum-k. This is O(n) time and works with negative numbers, unlike a sliding window. Use this hashing answer to show the decision, trade-off, and evidence rather than a memorised definition.

4 min readUpdated 2026-08-15

Answer

Short answer

Count subarrays summing to k by keeping a running prefix sum and a hash map from prefix-sum value to frequency. At each element, add the count for sum - k before recording the current sum, seed the map with {0: 1}, and use this instead of sliding window when numbers may be negative.

Was this answer helpful?

Likely follow-ups

  • Why does the two-pointer window work for this problem when all values are positive, and where exactly does it break otherwise?
  • Return the longest such subarray instead of the count. What changes in the map?
  • The keys here are boxed integers. What would you need from a custom key class?
  • When would you reject a hash map here and prefer sorting or an array?

Related questions

Further reading

Related Topics