Find the total number of continuous subarrays whose sum equals k.
Problem Statement
Examples
Input: nums = [1, 1, 1], k = 2
Output: 2
Explanation: Combining the input according to Count subarrays with given sum logic yields 2.
Input: nums = [1, 2, 3], k = 3
Output: 2
Explanation: Combining the input according to Count subarrays with given sum logic yields 2.
Input: nums = [3, 1, 2, 4], k = 6
Output: 2
Explanation: Combining the input according to Count subarrays with given sum logic yields 2.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
Editorial & Approach
Problem Overview & Intuition
If the cumulative sum up to index i is S, any previous prefix sum equal to S - K defines a valid contiguous subarray ending at i that sums to K. Storing frequencies in a Map allows answering each step in O(1).
Step-by-Step Approach
- Initialize
count = 0,currentSum = 0, andprefixMap = new Map([[0, 1]]). - Iterate through
numinnums. - Accumulate
currentSum += num. - If
prefixMap.has(currentSum - k), add its frequency tocount. - Increment frequency of
currentSumin the map. - Return
count.
Optimal Implementation (JavaScript)
function subarraySum(nums, k) {
let count = 0, currentSum = 0;
const prefixMap = new Map();
prefixMap.set(0, 1);
for (let num of nums) {
currentSum += num;
if (prefixMap.has(currentSum - k)) {
count += prefixMap.get(currentSum - k);
}
prefixMap.set(currentSum, (prefixMap.get(currentSum) || 0) + 1);
}
return count;
}
Complexity Analysis
Edge Cases & Corner Traps Handled
- k is negative.
- Array with multiple zeroes, giving multiple ways to form sum k.
- No valid subarray exists (returns 0).