DSA · Beginner · Pattern 5 of 11
Prefix Sum
11 problems.
Your progress0%
- 1st Visit
- 0/11
- 2nd Visit
- 0/11
- Revise
- 0/11
About this pattern
A prefix sum array stores pre[i], the total of the first i elements, so any subarray sum a[l..r] equals pre[r + 1] - pre[l] in O(1) after O(n) preprocessing. The same idea works for counts (how many positions up to i satisfy a condition) and for products taken from both sides. Combined with a hash map of earlier prefix values, it counts subarrays with a given sum in one pass.
Signals include many range-sum or range-count queries on a static array, subarrays whose sum equals or is divisible by a value, and a need for everything to the left and right of each index. Use long long to avoid overflow.
// pre[i] = a[0] + ... + a[i-1]; sum of a[l..r] = pre[r+1] - pre[l].
vector<long long> pre(n + 1, 0);
for (int i = 0; i < n; ++i) pre[i + 1] = pre[i] + a[i];
// Count subarrays whose sum equals k.
unordered_map<long long, int> cnt{{0, 1}};
long long count = 0;
for (int i = 1; i <= n; ++i) {
count += cnt[pre[i] - k];
cnt[pre[i]]++;
}