Subarray Sum Equals K
Difficulty: Medium
Given a list of numbers (which can include negatives) and a target k, count how many contiguous subarrays add up to exactly k.
A subarray's elements must sit next to each other in the list. You can't pick elements from scattered positions.
Examples
Input: nums = [1, 1, 1], k = 2
Output: 2
The subarray made of the first two elements, and the subarray made of the last two elements, both sum to 2.
Input: nums = [1, 2, 3], k = 3
Output: 2
The subarrays [1, 2] and [3] both sum to 3.
Input: nums = [1, -1, 0], k = 0
Output: 3
[1, -1], [0], and [1, -1, 0] all sum to 0.
Constraints
1 <= nums.length <= 2 * 10^4
-1000 <= nums[i] <= 1000
-10^7 <= k <= 10^7
Approach
Brute force sums every subarray and compares it to k. It works, but recomputes the same sums many times.
The faster approach uses prefix sums. A subarray's sum is the running total at its end minus the running total just before its start. So while scanning with a running total, ask at each step: "has (running total minus k) appeared as a running total before?" A hash map counting each running total answers this in one step, so one pass is enough.
Solutions
Brute Force - Check Every Subarray
From each starting position, extend the subarray one element at a time with a running sum. Count it whenever the sum equals k.
function subarraySum(nums, k) {
let count = 0;
for (let start = 0; start < nums.length; start++) {
let sum = 0;
for (let end = start; end < nums.length; end++) {
sum += nums[end];
if (sum === k) {
count++;
}
}
}
return count;
}Time: O(n²) · Space: O(1)
Optimal - Prefix Sum + Hash Map
Keep a running total and a hash map counting how often each running total has occurred. Seed it with 0 occurring once, so subarrays starting at index 0 are counted. At each step, the number of subarrays ending here that sum to k is how often (running total minus k) has appeared before.
function subarraySum(nums, k) {
const prefixCounts = new Map();
prefixCounts.set(0, 1); // an empty prefix sums to 0
let sum = 0;
let count = 0;
for (const num of nums) {
sum += num;
const needed = sum - k;
if (prefixCounts.has(needed)) {
count += prefixCounts.get(needed);
}
prefixCounts.set(sum, (prefixCounts.get(sum) || 0) + 1);
}
return count;
}Time: O(n) · Space: O(n)