Skip to main content

Prefix Sum

A prefix sum stores the cumulative total of a sequence up to each position. After one linear preprocessing pass, it lets you find the sum of any section of an array in constant time, without any repetitve addition.

Cost

It takes O(n) extra space. For a very large size of array this can be huge. Therefore effective only in situations where the number of range query is large and the array is fixed.

Pitfalls

  • Be consistent about whether ranges are inclusive or half-open. A leading zero makes [left, right) especially convenient.
  • Use a sufficiently wide numeric type when cumulative sums may exceed the range of individual elements.
  • Prefix sums work best for static data. If values change frequently, consider a Fenwick tree or segment tree instead.

Problem Patterns

PatternWhen to UseCore Idea
Range Sum QueryNeed sum of many subarrays/rangessum(L, R) = prefix[R + 1] - prefix[L]
Subarray Sum = KFind whether a subarray sums to KLook for an earlier prefix equal to currentPrefix - K
Count Subarrays with Sum = KCount all subarrays whose sum is KStore prefix-sum frequencies in a HashMap
Longest Subarray with Sum = KFind maximum-length subarray with sum KStore the earliest index of each prefix sum
Subarray Sum Divisible by KFind/count subarrays divisible by KEqual prefixSum % K values indicate a divisible subarray
Equal Count of Two ValuesFind subarray with equal occurrences of two valuesConvert one value to +1, the other to -1, then find zero-sum subarrays
Pivot / Equilibrium IndexFind index where left and right sums are equalCompare prefix sum with totalSum - prefixSum - nums[i]
Range Average QueryNeed average of many rangesGet range sum using prefix sum and divide by range length
2D Range SumNeed sum of rectangular regions in a matrixUse a 2D prefix-sum matrix
Range Frequency QueryCount occurrences of values/characters in a rangeMaintain prefix counts instead of prefix sums
Difference ArrayPerform many range updates efficientlyMark changes at range boundaries, then take prefix sum
Overlapping IntervalsCount how many intervals are active at each pointAdd at interval start, subtract after interval end, then prefix sum
Circular Array Range SumHandle ranges that wrap around the arrayCombine prefix sums with the total array sum

Interactive Visualization

Use the controls below to step through prefix-array construction and see how two prefix values answer each range-sum query.