Skip to the content.

27. Prefix Sums (Subarray Sum Equals K)

Back to the index

Precompute running totals so the sum of any range is one subtraction. Combined with a hash map, prefix sums count subarrays with a target sum in O(n), even with negative numbers.

How it works

Let prefix[i] be the sum of the first i items. Then the sum of items l through r is prefix[r + 1] - prefix[l]: one subtraction instead of a loop.

To count subarrays that sum to k, walk the array keeping the running prefix and a hash map of how many times each prefix value has appeared. A subarray ending here sums to k exactly when an earlier prefix equals prefix - k, so add that count. Start the map with {0: 1} so subarrays that begin at index 0 are counted.

Sliding windows cannot do this when numbers can be negative, because growing the window no longer only increases the sum.

Diagram

flowchart LR
    P0["prefix before l"] -->|"items l to r"| P1["prefix after r"]
    P1 --> S["range sum = prefix after r minus prefix before l"]
    S --> K{"equals k?"}
    K -->|"look up prefix minus k in the hash map"| C["add its count"]

Step-by-step trace

Input: nums = [1, 2, 3, -2, 2, 1], k = 3.

i num prefix need prefix - k times seen count seen map after
0 1 1 -2 0 0 0:1, 1:1
1 2 3 0 1 1 0:1, 1:1, 3:1
2 3 6 3 1 2 0:1, 1:1, 3:1, 6:1
3 -2 4 1 1 3 0:1, 1:1, 3:1, 4:1, 6:1
4 2 6 3 1 4 0:1, 1:1, 3:1, 4:1, 6:2
5 1 7 4 1 5 0:1, 1:1, 3:1, 4:1, 6:2, 7:1

Result: 5 subarrays sum to 3: [1, 2], [2, 3, -2], [3], [3, -2, 2], [2, 1].

Complexity

Operation Time Space
Build prefix array O(n) O(n)
Range sum query O(1) O(1)
Count subarrays with sum k O(n) O(n)

Python reference implementation

def count_subarrays_with_sum(nums, k):
    """Number of contiguous subarrays summing to k (works with negatives)."""
    seen = {0: 1}          # prefix sum -> how many times seen
    prefix = count = 0
    for x in nums:
        prefix += x
        count += seen.get(prefix - k, 0)
        seen[prefix] = seen.get(prefix, 0) + 1
    return count

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Sliding Window Next: Monotonic Stack (Next Greater Element)