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

Last updated on March 17, 2025 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. 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:

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

Example 2:

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", which can be solved using the hashing method.

The code is as follows

代码CPP · 20 行
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:

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.


A Common Pitfall When Using Prefix Sums to Solve the a-b Problem
https://blog.wendain.ing/en/posts/prefix-sum-pitfall-in-a-minus-b-problem/
Author
wendaining
Posted on
March 17, 2025
Updated on
March 17, 2025
Licensed under