medium

Subarray Sum Equals K

Count how many contiguous subarrays add up to a target value.

1. Define the problem

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

Inputnums = [1, 1, 1], k = 2
Output2

Explanation Two subarrays sum to 2: nums[0..1] = [1, 1] and nums[1..2] = [1, 1].

2. Know the words first

In plain terms

Contiguous subarray
A run of consecutive elements taken from the array without skipping any, like nums[2..4].
3. Visualize the solution

Check sum - k against a hashmap of running sums seen so far

Check sum - k against a hashmap of running sums seen so far
Statusinit

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}
Step 1 of 3

Steps to visualize

  1. Start a hashmap with {0: 1} — the empty prefix has been seen once.
  2. Walk the array, adding each value onto a running sum.
  3. At each index, add seenCount[sum - k] onto the answer, if that key exists.
  4. Increment seenCountsum to record this running sum for future indices.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Check sum - k against a hashmap of running sums seen so far
Statusinit

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}
Step 1 of 3
5. Solution

Solution

solution.tsTypeScript
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)
6. Test cases

Test cases

InputExpectedCovers
nums = [1, 1, 1], k = 22example from the docstring
nums = [1, 2, 3], k = 32a single-element match and a two-element match
nums = [1, -1, 0], k = 03negative values producing multiple zero-sum subarrays
nums = [1, 2, 3], k = 70target impossible to reach, no subarray matches
nums = [5], k = 51smallest valid input, one element equal to k
nums = [-1, -1, 1], k = 01all-negative values with exactly one zero-sum subarray