Subarray Sum Equals K: Prefix Sums + Hash Map
When an array contains negative numbers or zeroes, the standard sliding window (two-pointer) technique fails because subarray sums are non-monotonic: expanding a window might decrease the sum, and shrinking it might increase the sum.
Instead, we use a Running Prefix Sum combined with a Frequency Hash Map to achieve an optimal $O(n)$ time and $O(n)$ auxiliary space solution in a single pass.
The Mathematical Foundation
Let $\text{prefix}[i]$ denote the cumulative sum of elements from index $0$ to $i$:
$$\text{prefix}[i] = \sum_{m=0}^{i} \text{nums}[m]$$
The sum of any contiguous slice between index $j + 1$ and index $i$ is:
$$\text{sum}(j+1, i) = \text{prefix}[i] - \text{prefix}[j]$$
We want this contiguous subarray sum to equal $k$:
$$\text{prefix}[i] - \text{prefix}[j] = k \implies \text{prefix}[j] = \text{prefix}[i] - k$$
The Core Rule: As we compute the running sum $\text{prefix}[i]$, any earlier index $j$ that had a cumulative sum of $(\text{prefix}[i] - k)$ marks the start of a valid subarray ending at $i$. By storing the frequencies of all previous prefix sums in a hash map, we can instantly count how many such subarrays terminate at the current index in $O(1)$ time.
Why the Map Must Be Initialized with {0: 1}
Before processing any elements, we must register the base case: prefix_counts[0] = 1.
- The Problem: If a subarray starting at index $0$ sums up to $k$ directly (i.e., $\text{prefix}[i] = k$), the required target is: $$\text{target} = \text{prefix}[i] - k = k - k = 0$$
- The Solution: Inserting
{0: 1}represents the “empty prefix” before the array begins. It guarantees that whenever $\text{prefix}[i] == k$, the algorithm counts that complete slice from index $0$ to $i$.
Trace Walkthrough: nums = [1, -1, 1, 1, 1], k = 2
- Initial State:
map = {0: 1},current_sum = 0,count = 0
| Step | Num | current_sum |
Target (current_sum - k) |
Found in Map? | Tripped Subarrays | New Map State |
|---|---|---|---|---|---|---|
| 0 | 1 |
1 |
$1 - 2 = -1$ | No (0) | count += 0 |
{0:1, 1:1} |
| 1 | -1 |
0 |
$0 - 2 = -2$ | No (0) | count += 0 |
{0:2, 1:1} |
| 2 | 1 |
1 |
$1 - 2 = -1$ | No (0) | count += 0 |
{0:2, 1:2} |
| 3 | 1 |
2 |
$2 - 2 = 0$ | Yes (frequency = 2) | count += 2 |
{0:2, 1:2, 2:1} |
| 4 | 1 |
3 |
$3 - 2 = 1$ | Yes (frequency = 2) | count += 2 |
{0:2, 1:2, 2:1, 3:1} |
- Final Result:
4matching subarrays.
Implementations (C++ & Python)
C++ Implementation
#include <vector>
#include <unordered_map>
int subarraySum(const std::vector<int>& nums, int k) {
// Key: prefix sum, Value: frequency of occurrence
std::unordered_map<int, int> prefix_counts;
// Base case: handles subarrays starting at index 0 where prefix == k
prefix_counts[0] = 1;
int current_sum = 0;
int total_subarrays = 0;
for (int num : nums) {
current_sum += num;
// Check if there is an earlier prefix sum such that: current_sum - prefix = k
int target = current_sum - k;
if (prefix_counts.find(target) != prefix_counts.end()) {
total_subarrays += prefix_counts[target];
}
// Record the current prefix sum frequency
prefix_counts[current_sum]++;
}
return total_subarrays;
}
Python Implementation
def subarray_sum(nums: list[int], k: int) -> int:
# Key: prefix sum, Value: frequency of occurrence
prefix_counts = {0: 1} # Seed empty prefix base case
current_sum = 0
total_subarrays = 0
for num in nums:
current_sum += num
# If (current_sum - k) was observed previously, add its frequency
target = current_sum - k
if target in prefix_counts:
total_subarrays += prefix_counts[target]
# Register current prefix sum in the map
prefix_counts[current_sum] = prefix_counts.get(current_sum, 0) + 1
return total_subarrays
Complexity & Edge Case Behavior
| Metric | Complexity | Details |
|---|---|---|
| Time Complexity | $O(n)$ average | Single pass over the array of size $n$. Hash map lookups and insertions operate in $O(1)$ amortized time. |
| Space Complexity | $O(n)$ | In the worst case (distinct cumulative sums throughout), the map stores up to $n + 1$ unique prefix keys. |
- Zero Values: Handled seamlessly because zero elements increment the frequency of the existing prefix sum, naturally increasing counts for any subsequent valid window.
- Negative Values: Handled without special branching because hash lookups work symmetrically across positive and negative integer arithmetic.
