Subarray Sum Equals K
Given an array of integers nums and an integer k, return the total number of contiguous subarrays whose sum equals k . Keep a running sum and a hashmap of how many times each running sum value has occurred. At every index, sum - k already seen tells you exactly how many earlier stops complete a subarray ending here that sums to k.
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- -1000 ≤ numsi ≤ 1000
- -107 ≤ k ≤ 107
Example
nums = [1, 1, 1], k = 22Explanation Two subarrays sum to 2: nums[0..1] = [1, 1] and nums[1..2] = [1, 1].
In plain terms
- Contiguous subarray
- A run of consecutive elements taken from the array without skipping any, like nums[2..4].
Check sum - k against a hashmap of running sums seen so far
sum=1. Need sum-k=-1, not seen. count stays 0. Record sum=1.
What happens in this step
seenCount = {0: 1} sum = 0 count = 0
nums[0]=1: sum = 0 + 1 = 1
need sum-k = 1-2 = -1 → seenCount has no key -1 → add 0
count stays 0
seenCount[1] = (0 ?? 0) + 1 → seenCount = {0:1, 1:1}Steps to visualize
- Start a hashmap with {0: 1} — the empty prefix has been seen once.
- Walk the array, adding each value onto a running sum.
- At each index, add seenCount[sum - k] onto the answer, if that key exists.
- Increment seenCountsum to record this running sum for future indices.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
sum=1. Need sum-k=-1, not seen. count stays 0. Record sum=1.
What happens in this step
seenCount = {0: 1} sum = 0 count = 0
nums[0]=1: sum = 0 + 1 = 1
need sum-k = 1-2 = -1 → seenCount has no key -1 → add 0
count stays 0
seenCount[1] = (0 ?? 0) + 1 → seenCount = {0:1, 1:1}Solution
function subarraySum(nums, k) {
const seenCount = new Map([[0, 1]]);
let sum = 0;
let count = 0;
for (const value of nums) {
sum += value;
count += seenCount.get(sum - k) ?? 0;
seenCount.set(sum, (seenCount.get(sum) ?? 0) + 1);
}
return count;
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [1, 1, 1], k = 2 | 2 | example from the docstring |
nums = [1, 2, 3], k = 3 | 2 | a single-element match and a two-element match |
nums = [1, -1, 0], k = 0 | 3 | negative values producing multiple zero-sum subarrays |
nums = [1, 2, 3], k = 7 | 0 | target impossible to reach, no subarray matches |
nums = [5], k = 5 | 1 | smallest valid input, one element equal to k |
nums = [-1, -1, 1], k = 0 | 1 | all-negative values with exactly one zero-sum subarray |