Prefix sum arrays
22 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a program needs the sum of nums[left .. right] once, a simple loop is fine. When it needs the sum of q different ranges over the same static array, looping takes O(n · q) time—whereas precomputing a prefix sum array answers every range query in O(1) time after a single O(n) build pass.
Running totals
A prefix sum array stores, at each index i, the sum of all elements before i, so the sum of any range can be found in O(1) as prefix[r + 1] - prefix[l].
A prefix sum (also called a cumulative sum or running total) records the sum of all elements from the start of the array up to each position.
- Allocate long[] prefix = new long[nums.length + 1] (prefix[0] is automatically 0).
- Loop i from 0 to nums.length - 1.
- Set prefix[i + 1] = prefix[i] + nums[i].
Example 1 · Finding the pivot (equilibrium) index in O(n) time and O(1) extra space
public class PivotIndexDemo { public static int pivotIndex(int[] nums) { long totalSum = 0; for (int x : nums) { totalSum += x; } long leftSum = 0; for (int i = 0; i < nums.length; i++) { long rightSum = totalSum - leftSum - nums[i]; if (leftSum == rightSum) { return i; } leftSum += nums[i]; } return -1; }
public static void main(String[] args) { int[] a = {1, 7, 3, 6, 5, 6}; System.out.println("Pivot in [1,7,3,6,5,6]: " + pivotIndex(a)); int[] b = {2, 1, -1}; System.out.println("Pivot in [2,1,-1]: " + pivotIndex(b)); }}Pivot in [1,7,3,6,5,6]: 3 Pivot in [2,1,-1]: 0
What this code does
- At index i, the sum strictly to the left is leftSum, and the sum strictly to the right is totalSum - leftSum - nums[i].
- In [2, 1, -1], at index 0, leftSum is 0 and rightSum is 1 + (-1) = 0, so index 0 is the leftmost pivot.
Example 2 · Counting ways to split an array so left sum >= right sum
public class WaysToSplitArrayDemo { public static int waysToSplitArray(int[] nums) { long totalSum = 0; for (int x : nums) { totalSum += x; } long leftSum = 0; int validSplits = 0; for (int i = 0; i < nums.length - 1; i++) { leftSum += nums[i]; long rightSum = totalSum - leftSum; if (leftSum >= rightSum) { validSplits++; } } return validSplits; }
public static void main(String[] args) { int[] nums = {10, 4, -8, 7}; System.out.println("Valid splits: " + waysToSplitArray(nums)); }}Valid splits: 2
What this code does
- A split at index i (0 <= i < n - 1) puts nums[0..i] on the left and nums[i+1..n-1] on the right.
- Because we only scan left-to-right once, a running leftSum and precomputed totalSum replace the entire prefix array in O(1) space.
For example, if daily sales are nums = [3, 1, 4, 1, 5], the running totals after 0, 1, 2, 3, 4, and 5 days are prefix = [0, 3, 4, 8, 9, 14].
Notice how each entry builds directly on the previous entry in O(1) time:
prefix[i + 1] = prefix[i] + nums[i]
Building the entire prefix array takes one pass of n additions (O(n) time and O(n) space).
Range sum in O(1)
A range sum of nums[left .. right] (inclusive, 0 ≤ left ≤ right < n) takes a single subtraction once you have running totals: prefix[right + 1] - prefix[left].
public class RangeSum { public static void main(String[] args) { int[] nums = {3, 1, 4, 1, 5}; int[] prefix = new int[nums.length + 1]; // prefix[0] = 0 for (int i = 0; i < nums.length; i++) { prefix[i + 1] = prefix[i] + nums[i]; } int left = 1, right = 3; // [1, 4, 1] System.out.println(prefix[right + 1] - prefix[left]); }}6
Think of prefix[right + 1] as the sum of the first right + 1 elements (nums[0 .. right]), and prefix[left] as the sum of the first left elements (nums[0 .. left - 1]) just before our range starts. Subtracting the prefix before left cancels nums[0 .. left - 1] and leaves only nums[left .. right]:
Σ[k=left]^(right) nums[k] = prefix[right + 1] - prefix[left]
In our example nums = [3, 1, 4, 1, 5] (prefix = [0, 3, 4, 8, 9, 14]), the sum of indices 1 .. 3 ([1, 4, 1]) is prefix[4] - prefix[1] = 9 - 3 = 6.
- Build cost: O(n) time, O(n) space.
- Per-query cost: O(1) time (one array subtraction).
- Total cost for q queries: O(n + q) instead of O(n * q).
Prefix sums of [3, 1, 4, 1, 5] and the range 1 to 3
Step 1 of 4
- 0
Predict the output
Answer one range query
Work out the printed sum.
prefix[k] is the sum of the first k numbers. What does this code print?
Avoiding off-by-one with size n + 1
Beginners often allocate a prefix array of length n where P[i] = nums[0] + ... + nums[i]. That works, but querying left .. right requires an awkward branch every time: left == 0 ? P[right] : P[right] - P[left - 1].
Example 3 · Brute force: add up the range for every query (O(n) per query, O(1) space)
public class RangeSumBrute { static class NumArray { private final int[] nums;
NumArray(int[] nums) { this.nums = nums; }
public long sumRange(int left, int right) { long sum = 0; for (int i = left; i <= right; i++) { sum += nums[i]; } return sum; } }
public static void main(String[] args) { int[] nums = {-2, 0, 3, -5, 2, -1}; NumArray queryEngine = new NumArray(nums); System.out.println("sumRange(0, 2): " + queryEngine.sumRange(0, 2)); System.out.println("sumRange(2, 5): " + queryEngine.sumRange(2, 5)); System.out.println("sumRange(0, 5): " + queryEngine.sumRange(0, 5)); }}sumRange(0, 2): 1 sumRange(2, 5): -1 sumRange(0, 5): -3
What this code does
- Each query loops over its whole range, so q queries on an array of n numbers cost up to O(n · q).
- The array never changes between queries, so the same partial sums are added again and again. Saving them once removes that repeated work.
Example 4 · Optimal: build a padded prefix array once, answer each query in O(1) (O(n) build, O(n) space)
import java.util.Arrays;
public class PrefixSumQueryDemo { static class NumArray { private final long[] prefix;
NumArray(int[] nums) { this.prefix = new long[nums.length + 1]; for (int i = 0; i < nums.length; i++) { prefix[i + 1] = prefix[i] + nums[i]; } }
public long sumRange(int left, int right) { return prefix[right + 1] - prefix[left]; } }
public static void main(String[] args) { int[] nums = {-2, 0, 3, -5, 2, -1}; NumArray queryEngine = new NumArray(nums); System.out.println("prefix: " + Arrays.toString(queryEngine.prefix)); System.out.println("sumRange(0, 2): " + queryEngine.sumRange(0, 2)); System.out.println("sumRange(2, 5): " + queryEngine.sumRange(2, 5)); System.out.println("sumRange(0, 5): " + queryEngine.sumRange(0, 5)); }}prefix: [0, -2, -2, 1, -4, -2, -3] sumRange(0, 2): 1 sumRange(2, 5): -1 sumRange(0, 5): -3
What this code does
- Notice that prefix sums work seamlessly with negative numbers because addition and subtraction are exact inverses.
- When left = 0, sumRange(0, 2) computes prefix[3] - prefix[0] = 1 - 0 = 1 without any special-case if statement.
- Why it is faster: the O(n) build is paid once, and every query is then one subtraction. For q queries the total is O(n + q) instead of O(n · q).
Worse, forgetting the left == 0 check crashes with ArrayIndexOutOfBoundsException: Index -1.
By allocating prefix with length n + 1 and keeping prefix[0] = 0 as the sum of the empty prefix (0 elements), prefix[k] always means "the sum of the first k elements". Then prefix[right + 1] - prefix[left] works for every valid range, including left == 0 (prefix[right + 1] - prefix[0]), with zero branches!
How to spot this pattern
Look for these clues in the problem statement.
- Many range sum questions are asked about an array that does not change: build prefix sums once.
- The answer needs the sum or count between two positions, or "left part equals right part" (pivot index).
- A subarray must add up to k or be divisible by k: prefix sums plus a map of earlier sums.
- Many updates add the same value to a range, and only the final array matters: a difference array.
Next step
Check your understanding
10 quick questions