Subarray Sum Equals K
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k. A subarray is a contiguous non-empty sequence of elements within an array.
Sample Input: nums = [1, 2, 3], k = 3
Expected Output: 2
The subarrays are [1, 2] and [3].
Constraints
1 <= nums.length <= 2 * 104-1000 <= nums[i] <= 1000-107 <= k <= 107
How We Solve This
- Compute running sums (prefix sums) as we iterate through the array.
- Use a HashMap to remember how many times each prefix sum has occurred.
- For each new prefix sum, check if
(currentSum - k)exists in the HashMap:- If yes, add its count to the answer (it represents subarrays ending at the current index that sum to k).
- Update the HashMap with the current prefix sum.
Edge Cases to Consider
Empty Array
Input:
[]k:
3Output:
0No subarrays can be formed, so the count is 0.
No Matching Subarrays
Input:
[1, 2, 4]k:
10Output:
0Correctly returns 0 when no subarray sums to k.
All Zeros
Input:
[0, 0, 0]k:
0Output:
6Counts multiple overlapping subarrays of zeros.
Includes Negatives
Input:
[1, -1, 2]k:
2Output:
2Handles negative numbers correctly in prefix sums.
Single Element Array
Input:
[3]k:
3Output:
1A single element can be a valid subarray.