AlgoMaster Logo

Subarray Sum Equals K

mediumFrequency5 min readUpdated June 23, 2026

Understanding the Problem

We need to count every contiguous subarray that sums to exactly k. The task is the total count, not a single subarray or the longest one.

A subarray is defined by its start and end indices. For an array of length n, there are n * (n + 1) / 2 possible subarrays. The brute force approach checks every single one, but can we do better?

There is a faster way using cumulative sums. If we know the cumulative sum from index 0 to index j (call it prefixSum[j]), and the cumulative sum from index 0 to some earlier index i (call it prefixSum[i]), then the sum of the subarray from i+1 to j is prefixSum[j] - prefixSum[i]. When that difference equals k, the subarray is valid. So for each position j, we count how many earlier prefix sums equal prefixSum[j] - k.

Key Constraints:

  • nums.length up to 2 * 10^4 puts O(n^2) at about 4 * 10^8 operations in the worst case, which is too slow, so an O(n) solution is preferred
  • Elements can be negative (-1000 <= nums[i] <= 1000), which rules out sliding window approaches that rely on the sum growing as the window expands
  • k can be negative too, so we cannot assume anything about the target sum's sign

Approach 1: Brute Force

Intuition

Try every possible subarray, compute its sum, and check if it equals k. We fix a starting index i, then extend the subarray one element at a time to each ending index j. Keeping a running sum as we extend avoids recomputing the sum from scratch each time.

Algorithm

  1. Initialize a counter count to 0
  2. For each starting index i from 0 to n-1:
    • Initialize sum to 0
    • For each ending index j from i to n-1:
      • Add nums[j] to sum
      • If sum equals k, increment count
  3. Return count

Example Walkthrough

1i=0, j=0: sum=1, k=3. sum!=k. count=0
0
i
1
j
1
2
2
3
1/7

Code

The repeated forward scans are the cost. The next approach computes the prefix sum in a single pass and uses a hash map to look up, in O(1), how many earlier prefix sums form a valid subarray ending at the current position.

Approach 2: Prefix Sum + Hash Map

Intuition

The sum of a subarray from index i+1 to index j equals prefixSum[j] - prefixSum[i]. For this to equal k, we need prefixSum[i] = prefixSum[j] - k. So as we walk through the array building up the prefix sum, at each position j we count how many earlier prefix sums equal currentPrefixSum - k.

We track those frequencies in a hash map and initialize it with {0: 1}. That entry accounts for subarrays starting at index 0, where the prefix sum itself equals k (and prefixSum - k is therefore 0).

Algorithm

  1. Initialize count = 0, prefixSum = 0, and a hash map prefixCount with {0: 1}
  2. For each element num in the array:
    • Add num to prefixSum
    • If prefixSum - k exists in prefixCount, add its frequency to count
    • Increment prefixCount[prefixSum] by 1
  3. Return count

Example Walkthrough

1Init: prefixSum=0, count=0, map={0:1}
0
1
i
1
2
2
3
1/6

Code