Skip to content
We areTOP 1%
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]]++;
}

Problems

Prefix Sum questions
#ProblemPlatformDifficultyOpen1st1st Visit2nd2nd VisitRevRevise
1Running Sum of 1d ArrayLeetCodeEasy Solve Running Sum of 1d Array on LeetCode (opens in a new tab)
2Find Pivot IndexLeetCodeEasy Solve Find Pivot Index on LeetCode (opens in a new tab)
3Range Sum Query - ImmutableLeetCodeEasy Solve Range Sum Query - Immutable on LeetCode (opens in a new tab)
4Odd QueriesCodeforcesEasy 900Solve Odd Queries on Codeforces (opens in a new tab)
5Distinct SplitCodeforcesEasy 1000Solve Distinct Split on Codeforces (opens in a new tab)
6Ilya and QueriesCodeforcesEasy 1100Solve Ilya and Queries on Codeforces (opens in a new tab)
7Sereja and SuffixesCodeforcesEasy 1100Solve Sereja and Suffixes on Codeforces (opens in a new tab)
8Kuriyama Mirai's StonesCodeforcesEasy 1200Solve Kuriyama Mirai's Stones on Codeforces (opens in a new tab)
9Range Sum Query 2D - ImmutableLeetCodeMedium Solve Range Sum Query 2D - Immutable on LeetCode (opens in a new tab)
10Product of Array Except SelfLeetCodeMedium Solve Product of Array Except Self on LeetCode (opens in a new tab)
11Subarray Sum Equals KLeetCodeMedium Solve Subarray Sum Equals K on LeetCode (opens in a new tab)

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account