Subarray Sum Equals K
Medium
Given an integer array nums and an integer k, return the total number of subarrays whose sum is equal to k.
A subarray is a contiguous part of the array containing at least one element.
Example 1
Input
nums = [1, 1, 1] k = 2
Output
2
Explanation
The subarrays whose sum is 2 are:
[1, 1]
[1, 1]
Therefore, the answer is 2.
Example 2
Input
nums = [1, 2, 3] k = 3
Output
2
Explanation
The valid subarrays are:
[1, 2]
[3]
Both have sum 3.
Constraints
1 <= nums.length <= 20000
-1000 <= nums[i] <= 1000
-10^7 <= k <= 10^7
Hints:
Hint 1
Use a running prefix sum while traversing the array.
Hint 2
If the current prefix sum is sum, a previous prefix sum of:
sum - k
means the subarray between those two positions has sum k.
Auto
Loading editor...
Input
Expected Output