pnkjsng
DSAArraysPrefix SumCh.1

Prefix Sum Pattern

·

Prefix sum pattern on Arrays

When we want to work on a range [l, r] or subarray[l,r] or substring[l,r], many a times we can pre-compute some operation of the array/string one time and efficiently query a response for a given range. If this is what we need to do, we can use prefix-sum pattern.

Prefix sum efficiently solves frequent reads across a range but not frequent writes (updates) — the array must not change after pre-computation. If the problem asks for frequent updates as well, a Segment Tree is a better option as it supports both read/write across a range in O(log N).

Precompute cumulative sum so any range sum [L,R] is answered in O(1) instead of O(N).

prefix[i] = arr[0] + arr[1] + ... + arr[i]

sum(L, R) = prefix[R] - prefix[L-1]

Build: O(N) Query: O(1) → This is where PrefixSum shines.

Template code for 1-D prefix Sum:

// One time operation
int[] buildPrefix(int[] arr) {
    int n = arr.length;
    int[] prefix = new int[n + 1];
    for (int i = 0; i < n; i++)
        prefix[i + 1] = prefix[i] + arr[i];
    return prefix;
}

// Query sum of arr[l..r] (0-indexed, inclusive) -> Constant time operation
int query(int[] prefix, int l, int r) {
    return prefix[r + 1] - prefix[l];
}

Variations:

If we need to track cumulative sum from the right side (Suffix) as well, we can first calculate the total sum and maintain a running prefixSum so that at each point:

prefixSum = running prefixSum

suffixSum = totalSum - prefixSum

Problems to practice:

# Problem Difficulty Done
1 Range Sum Query - Immutable Easy
2 Running Sum of 1D Array Easy
3 Find Pivot Index Easy
4 Find the Highest Altitude Easy
5 Find the Pivot Integer Easy
6 Maximum Score After Splitting a String Easy
7 Sum of All Odd Length Subarrays Easy
8 Left and Right Sum Differences Easy