Prefix Sum — The Complete Guide
Master the Prefix Sum pattern from first principles. Learn to recognize it instantly, evolve brute-force into optimal solutions, and confidently solve interview questions.
Intuition from Scratch
Why does this pattern exist?
Imagine you're a teacher and you have a list of daily test scores for a student over the entire year. A parent asks: "What was the average score between March 10 and April 20?" You could add up every score in that range from scratch. But what if they ask again for a different range? And again? Each time you'd re-add dozens of numbers.
Instead, you could keep a running total — after day 1 the total is 85, after day 2 it's 170, after day 3 it's 248, and so on. Now to find the sum between any two days, you just subtract two numbers: sum(i, j) = runningTotal[j] − runningTotal[i − 1]. One subtraction instead of adding up the entire range. That running total is a prefix sum.
The pattern exists because many problems ask about range sums or subarray sums. Computing them from scratch each time is O(n) per query. Precomputing a prefix sum array makes each query O(1) — you trade O(n) space for unlimited O(1) queries.
Analogies to Build Intuition
The Bank Balance
Your bank balance is a prefix sum of all your transactions. To find how much you spent between Tuesday and Friday, you don't re-add every transaction — you just subtract Tuesday's balance from Friday's balance. One subtraction, instant answer.
The Odometer
A car's odometer tracks total distance driven. To find how far you drove between two gas stations, subtract the odometer reading at the first station from the reading at the second. The odometer IS a prefix sum of all the small distances you've driven.
The Cumulative Frequency Table
In statistics, a cumulative frequency table stores running totals. To find how many values fall in a range, subtract two cumulative frequencies. Same idea — precompute once, query instantly.
What kind of problems does it solve?
Prefix Sum is your go-to when:
- You need the sum of a subarray from index i to j
- You need to answer multiple range sum queries on the same array
- You need to count subarrays with a specific sum
- You need prefix/suffix products (Product of Array Except Self)
- You need to check if a subarray sum is divisible by k
The core insight
Prefix Sum converts range sum queries from O(n) to O(1) by precomputing cumulative totals. The formula is simple: sum(i, j) = prefix[j + 1] − prefix[i]. Build once in O(n), query unlimited times in O(1).