9. Subarray Sum Equals K

Count the contiguous subarrays of nums whose elements add up to exactly k. Values can be negative.

Example 1

Input: nums = [1,2,3,-2,2], k = 3
Output: 4
Explanation: [1,2], [3], [2,3,-2] and [3,-2,2] all sum to 3.

Example 2

Input: nums = [1,-1,0], k = 0
Output: 3

Constraints

  • 1 ≤ nums.length ≤ 2·10⁴
  • -1000 ≤ nums[i] ≤ 1000
Hint 1

sum(i..j) = prefix[j] − prefix[i−1].

Hint 2

So for each prefix, count how many earlier prefixes equal prefix − k.

Hint 3

Sliding window does NOT work here because values can be negative.

Prefix SumHash Table