Skip to problem
←

Subarray Sum Equals K

Medium 0 attempts

You're given an array of integers nums and an integer k. Count how many contiguous, non-empty slices of the array (subarrays) have elements that add up to exactly k.

Count subarrays by their start and end indices. Overlapping subarrays count separately, even when they contain the same values. The empty subarray never counts. For three zeros, all six nonempty subarrays sum to k = 0.

Function contract

Implement subarraySum(nums, k).

Output: Return the number of nonempty contiguous subarrays whose sum equals k.

Example 1

Input
nums = [1,1,1]
k = 2
Output
2

Example 2

Input
nums = [1,-1,0]
k = 0
Output
3
Constraints
  • 1 <= nums.length <= 2 * 10^4
  • -1000 <= nums[i] <= 1000
  • -10^7 <= k <= 10^7

Use a hash map to store prefix sums and their frequencies. At each index, check if currentSum - k exists in the map — if so, those many subarrays ending here sum to k.

Seed the empty prefix with frequency 1 so subarrays starting at index 0 are counted. Count matches before recording the current prefix; reversing that order would count an empty subarray. Frequencies, rather than a set, preserve multiple valid starting indices.

javascript
function subarraySum(nums, k) {
  const prefixCount = new Map([[0, 1]]);
  let sum = 0, count = 0;

  for (const num of nums) {
    sum += num;
    if (prefixCount.has(sum - k)) {
      count += prefixCount.get(sum - k);
    }
    prefixCount.set(sum, (prefixCount.get(sum) || 0) + 1);
  }

  return count;
}

Time: O(n) Space: O(n)

Negative values mean extending a window can increase or decrease its sum, so a standard positive-only sliding-window method does not apply.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript