# A Common Pitfall When Using Prefix Sums to Solve the a-b Problem

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/prefix-sum-pitfall-in-a-minus-b-problem/>). I am continuously working to improve the translation.

# Problem

Given an integer array `nums` and an integer `k`, please count and return *the number of subarrays in this array whose sum equals `k`*.

A subarray is a contiguous non-empty sequence of elements in the array.

**Example 1:**

```md
Input: nums = [1,1,1], k = 2
Output: 2
```

**Example 2:**

```md
Input: nums = [1,2,3], k = 3
Output: 2
```

**Constraints:**

- `1 <= nums.length <= 2 * 104`
- `-1000 <= nums[i] <= 1000`
- `-107 <= k <= 107`
# Solution

It is easy to think of using a prefix sum array `presum[]` to handle this, converting the sum of contiguous subarrays within an interval into differences of prefix sums. This transforms it into the A-B problem ["Binary Search, Hashing, and Two-Pointer Approaches to the 'A-B' Problem"](https://kiriaotj.github.io/2025/03/04/2025-03-04-%E2%80%9CA-B%E2%80%9D%E9%97%AE%E9%A2%98%E7%9A%84%E4%BA%8C%E5%88%86%E3%80%81%E5%93%88%E5%B8%8C%E3%80%81%E5%8F%8C%E6%8C%87%E9%92%88%E5%86%99%E6%B3%95/), which can be solved using the hashing method.

The code is as follows

```cpp
class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int n=nums.size();
        vector<int> presum(n+1,0);
        presum[0]=0;
        unordered_map<int,int> mp;
        for(int i=1;i<=n;i++){
            presum[i]=presum[i-1]+nums[i-1];
        }
        for(int x:presum){
            mp[x]++;
        }
        int ans=0;
        for(int x:presum){
            ans+=mp[x-k];
        }
        return ans;
    }
};
```

However, there is a problem here! When nums={1}, k=0, it incorrectly returns 2. This is because: storing all prefix sums into the hash table at once, including the currently processed prefix sum `sum` itself, causes self-counting when sum - k equals sum (for example, when k=0), resulting in an incorrect count. For example, when sum=0, during the first traversal of the presum array, the hash table already contains this sum=0. When processing it, x-k=0, so it gets counted at least once, even though there may be no earlier prefix sum corresponding to this sum's position.

Correcting the code:

```cpp
class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        int pre=0;
        int ans=0;
        unordered_map<int,int> cnt;
        cnt[0]=1; //！！初始化前缀和为 0 的次数为 1
        for(int x:nums){
            pre+=x;
            ans+=cnt[pre-k];
            cnt[pre]++;
        }
        return ans;
    }
};
```

The key point is to **avoid self-matching**: when computing `ans+=cnt[pre-k]`, the hash table only contains prefix sums from **before** the current element, ensuring that the current prefix sum itself is not counted in the result.
