AlgoMaster Logo

Subarray Sum Equals K

Last Updated: March 21, 2026

medium
3 min read

Understanding the Problem

We need to count every contiguous subarray that sums to exactly k. Not find one, not find the longest, but count all of them.

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?

The key observation is this: if we know the cumulative sum from index 0 to index j (call it prefixSum[j]), and we know 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 simply prefixSum[j] - prefixSum[i]. If that difference equals k, we've found a valid subarray. So the question becomes: for each position j, how many earlier prefix sums equal prefixSum[j] - k?

Key Constraints:

  • nums.length up to 2 * 10^4 means O(n^2) is borderline (about 4 \* 10^8 operations in the worst case), 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 can't make assumptions about the target sum's sign

Approach 1: Brute Force

Intuition

The most direct approach: 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. By keeping a running sum as we extend, we avoid 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

For every starting index, we scan forward through the rest of the array. What if we computed the prefix sum once and used a hash map to instantly look up how many earlier prefix sums would 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 can be written as prefixSum[j] - prefixSum[i]. If we want this to equal k, we need prefixSum[i] = prefixSum[j] - k. So as we walk through the array building up our prefix sum, at each position j we ask: "How many times have I seen a prefix sum equal to currentPrefixSum - k?"

We track these frequencies in a hash map. One crucial detail: we initialize the map with {0: 1}. This accounts for subarrays that start from the very beginning of the array (where the prefix sum itself equals k).

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