Subarray Sum Equals K
MediumHash Map · Meta
You are given an integer array nums and an integer k. Return the number of contiguous, non-empty subarrays whose elements sum to exactly k.
Subarrays are counted by position: two subarrays with the same values but different start or end indices are counted separately. The array may contain negative numbers and zeros.
Example 1
- Input:
- nums = [3, 4, 7, 2, -3, 1, 4, 2], k = 7
- Output:
- 4
- Explanation
- Four subarrays sum to 7:
[3, 4],[7],[7, 2, -3, 1]and[1, 4, 2]. Because of the-3, two of them start at the same7.
Example 2
- Input:
- nums = [1, -1, 0], k = 0
- Output:
- 3
- Explanation
- Three subarrays sum to 0:
[1, -1],[1, -1, 0]and[0]. Zeros and negatives let one zero-sum subarray contain another.
Example 3
- Input:
- nums = [2, 2, 2], k = 3
- Output:
- 0
- Explanation
- Every subarray sums to an even number, so none of them equals 3.
Constraints
- 1 ≤
nums.length≤ 2 * 104 - -1000 ≤
nums[i]≤ 1000 - -107 ≤
k≤ 107