Subarray Sum Equals K
Given an integer array nums and an integer k, return the **total number of contiguous subarrays** whose elements sum to exactly k.
The array may contain negative numbers and zeros, so you can't rely on a sliding window — a longer subarray isn't guaranteed to have a larger sum.
Example cases
- two subarraysin nums = [1,1,1], k = 2out 2[1,1] at indices 0..1 and 1..2.
- single hitin nums = [1,2,3], k = 3out 2[3] and [1,2] both sum to 3.
- with negativesin nums = [1,-1,0], k = 0out 3[1,-1], [0], and [1,-1,0] all sum to 0.
- no subarrayin nums = [1,2,3], k = 7out 0
Constraints
- 1 <= nums.length <= 2 * 10^4
- -1000 <= nums[i] <= 1000
- -10^7 <= k <= 10^7
nums =
[1,1,1]
k =
2