Builds onArrays and stringsHash map lookup
01The idea
A prefix sum array stores running totals. prefix[i] is the sum of the first i items, and prefix[0] is 0:
nums = [2, 3, 4, 1, 4]
prefix = [0, 2, 5, 9, 10, 14]
You build it in one pass, because each total is the one before it plus one item: prefix[i + 1] = prefix[i] + nums[i].
After that, the sum of any stretch takes O(1). The sum of the items from index l to index r, both included, is:
prefix[r + 1] - prefix[l]
The first total covers everything up to r. Subtracting the second removes everything before l. What is left is exactly the stretch from l to r.
So one O(n) pass of preparation turns every range-sum question into a subtraction. Without it, each question would need a loop over the range.
02How to spot it
Use prefix sums when:
- the problem asks for the sum of many different ranges of the same array
- it compares the sum on one side of an index with the sum on the other side
- it asks for subarrays with a given sum and the items can be negative, which rules out a sliding window
The last case pairs prefix sums with a hash map. A subarray from l to r sums to k exactly when prefix[r + 1] - prefix[l] equals k. Walk the array, and for each running total look up how many earlier totals equal total - k. You will meet this in the hash map problems.
The same idea works on a grid. A 2D prefix array gives the sum of any rectangle in O(1).
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue