Count subarrays with sum exactly k. nums may contain negative numbers. Which approach is correct in O(n)?
Show answer
Answer
Prefix sums with a hash map of prefix counts
With negatives, extending a window can lower the sum, so the shrink rule is not monotonic and a window misses answers. Counting earlier prefixes equal to prefix minus k handles any values. A fixed size k window confuses the target with a length. Sorting destroys contiguity.