Quick reference
A prefix sum is a running total:
prefix[i] is the sum of the first i
items of an array. Once you've built the
prefix sum array in
O(n) time, the sum of any contiguous range
is the difference of two prefix sums, which takes
O(1) time.
The formulas:
-
prefix[0] = 0andprefix[i + 1] = prefix[i] + nums[i], so the prefix sum array has n + 1 entries. -
Sum of
nums[i]up to (not including)nums[j]=prefix[j] - prefix[i]. -
Sum of
nums[left]throughnums[right]=prefix[right + 1] - prefix[left].
When to use it:
- You need the sums of many ranges of an array that doesn't change.
- You need to count or find subarrays with a given sum, especially when the numbers can be negative. Pair prefix sums with a hash map.
Cost:
- O(n) time and O(n) space to build, then O(1) time per range sum.
How Prefix Sums Work
A bakery sold [4, 2, 7, 1, 5] cakes on days 0 through 4. How many did it sell from day 1 through day 3? You could add 2 + 7 + 1 = 10. But if you have to answer thousands of questions like that, adding up every range from scratch costs O(n) time per question.
Instead, work out the running totals once. prefix[i] is
the number of cakes sold before day
i:
| i | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
nums[i] (sold on day i) |
4 | 2 | 7 | 1 | 5 | |
prefix[i] (sold before day i) |
0 | 4 | 6 | 13 | 14 | 19 |
Each entry is the one before it plus one more day:
prefix[3] = prefix[2] + nums[2]
= 6 + 7 = 13. Now any range is one subtraction. Sales from day 1
through day 3 are everything sold before day 4, minus everything sold
before day 1:
prefix[4] - prefix[1] = 14 − 4 = 10
In general, prefix[right + 1] adds up
nums[0] through nums[right], and
prefix[left] adds up nums[0] through
nums[left - 1]. Subtracting cancels everything before
left and leaves exactly nums[left] through
nums[right].
Why the Prefix Sum Array Has n + 1 Entries
Prefix sums are a classic place for off-by-one bugs, and most of them come from mixing up two conventions. We recommend the first one:
Length n + 1, prefix[0] = 0 (recommended) |
Length n, prefix[i] includes nums[i]
|
|
|---|---|---|
prefix[i] means |
The sum of the first i numbers (everything before index i) | The sum of nums[0] through nums[i]
|
| For [4, 2, 7, 1, 5] | [0, 4, 6, 13, 14, 19] | [4, 6, 13, 14, 19] |
Sum of nums[left] through nums[right]
|
prefix[right + 1] - prefix[left] |
prefix[right] - prefix[left - 1], which breaks when left is 0 |
| Range that starts at index 0 | Same formula | Needs a special case |
The extra 0 at the front is the sum of no numbers.
With it, a range that starts at index 0 subtracts
prefix[0] = 0 like any other range, so there's no
if statement to forget. An empty range comes out right
too: prefix[i] - prefix[i] is 0.
It also matches the half-open ranges that slices use:
prefix[j] - prefix[i] is the sum of the
j - i numbers from index i up to
but not including index j, the same numbers
as Python's nums[i:j] or JavaScript's
nums.slice(i, j).
Subarray Sum Equals K: Prefix Sums with a Hash Map
Example problem: count the contiguous subarrays of
nums that add up to k. The numbers can
be negative.
Checking every start and end takes
O(n²) time, even with a running sum.
Prefix sums do better. The subarray from index i up
to (not including) index j adds up to
prefix[j] - prefix[i]. We want that to equal
k, which means:
prefix[i] = prefix[j] - k
So walk through the numbers keeping a running sum, which is
prefix[j], and a hash map that counts how many times
each prefix sum has shown up so far. At each step, every earlier
prefix sum equal to runningSum - k is the start of a
subarray that ends here and adds up to k. The map
starts with {0: 1} for the empty prefix, so subarrays that start at
index 0 count too.
Here it is on [2, −1, 1, 2] with k = 2:
| Index | Number | Running sum | Look for running sum − 2 | Seen before (subarrays found) | Count | Map after |
|---|---|---|---|---|---|---|
| Start | 0 | 0 | {0: 1} | |||
| 0 | 2 | 2 | 0 | 1: [2] | 1 | {0: 1, 2: 1} |
| 1 | −1 | 1 | −1 | 0 | 1 | {0: 1, 2: 1, 1: 1} |
| 2 | 1 | 2 | 0 | 1: [2, −1, 1] | 2 | {0: 1, 2: 2, 1: 1} |
| 3 | 2 | 4 | 2 | 2: [−1, 1, 2] and [2] | 4 | {0: 1, 2: 2, 1: 1, 4: 1} |
The answer is 4. At index 3, the running sum is 4, so we look for 4 − 2 = 2. That running sum showed up twice before: after index 0, so the numbers after it, [−1, 1, 2], add up to 2, and after index 2, so [2] on its own adds up to 2.
That's O(n) time and
O(n) space for the hash map. Two details
matter. Look up runningSum - k before recording
the current running sum. Otherwise, when k = 0, the
current prefix pairs with itself and you count an empty subarray. And
the map counts how many times each sum appeared, not just whether it
did, because with negatives and zeros the same prefix sum can show up
many times.
Why not a sliding window?
A sliding window shrinks from the left when its sum gets too big, and never looks back. That only works if adding a number never lowers the sum, which means no negative numbers. Here, a "shrink while the sum is bigger than k" window counts only 3 subarrays in [2, −1, 1, 2]. When it reaches the last 2, the sum is 4, so it drops the first 2 and counts [−1, 1, 2]. Then the sum is 2, so it stops shrinking and never finds [2] on its own.
Zeros cause trouble too, since several different starts can give the same sum for one end. The hash map doesn't care: it checks every possible start at once, whatever the numbers are. If all the numbers are positive, though, a sliding window works and uses only O(1) space.
2-D Prefix Sums
The same idea works on a grid. Let prefix[r][c] be the
sum of every cell in rows 0 through r - 1 and
columns 0 through c - 1, the rectangle above and to
the left of row r, column c. Like
the 1-D version, it has an extra row and column of zeros at the top
and left.
Take this grid:
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
Its 2-D prefix sums are:
| c = 0 | c = 1 | c = 2 | c = 3 | |
|---|---|---|---|---|
| r = 0 | 0 | 0 | 0 | 0 |
| r = 1 | 0 | 1 | 3 | 6 |
| r = 2 | 0 | 5 | 12 | 21 |
| r = 3 | 0 | 12 | 27 | 45 |
Building it uses inclusion-exclusion. Each entry is its own cell, plus everything above, plus everything to the left, minus the top-left block, which got added twice:
prefix[r + 1][c + 1] = grid[r][c] + prefix[r][c + 1] + prefix[r + 1][c] - prefix[r][c]
For example, prefix[2][2] = 5 + 3 + 5 − 1 = 12,
which is 1 + 2 + 4 + 5.
Querying any rectangle takes four lookups. For the bottom-right 2×2 block (rows 1 to 2, columns 1 to 2, which is 5 + 6 + 8 + 9 = 28):
-
Start with everything up to the bottom-right corner:
prefix[3][3]= 45. -
Subtract the rows above the rectangle:
prefix[1][3]= 6. -
Subtract the columns to its left:
prefix[3][1]= 12. -
The top-left corner was in both of those, so it got subtracted
twice. Add it back once:
prefix[1][1]= 1.
45 − 6 − 12 + 1 = 28. For a grid with m rows and n columns, building the table takes O(m · n) time and space, and every rectangle query after that is O(1).
Difference Arrays: Range Updates in O(1)
A difference array is the inverse of a prefix sum. It stores how much each value changes from the one before it, and taking its prefix sums (its running total) gives the values back. It's the tool for the opposite problem: lots of updates to ranges, then one read of every value at the end.
Example problem: each order to the bakery asks for some number of cakes every day from a first day through a last day. How many cakes are needed on each day?
Adding an order to every day in its range costs
O(n) per order. With a difference array,
adding amount to left through
right only changes two entries: the values jump up by
amount at left, and back down right after
right.
diff[left] += amountdiff[right + 1] -= amount
Take 5 days and two orders: 2 cakes a day for days 0 to 2, and 3
cakes a day for days 1 to 4. The difference array gets one extra slot
so that right + 1 never falls off the end:
| Day | 0 | 1 | 2 | 3 | 4 | (5) |
|---|---|---|---|---|---|---|
| After order 1 (days 0 to 2, +2) | 2 | 0 | 0 | −2 | 0 | 0 |
| After order 2 (days 1 to 4, +3) | 2 | 3 | 0 | −2 | 0 | −3 |
| Running total (cakes needed) | 2 | 5 | 5 | 3 | 3 |
Each update is O(1), and turning the difference array back into values is one O(n) pass at the end. Problems like flight bookings, car pooling, and "how many meetings are going on at each time" use this trick. The same idea works in 2-D: add at one corner, subtract at two, and add back at the fourth.
Prefix XOR, Prefix Products, and Other Variants
A running total works for any operation you can
undo. Subtraction undoes addition, which is what
lets prefix[j] - prefix[i] cancel the shared part.
Here's how other operations do:
-
Prefix counts. Count something instead of adding values: how many vowels, 1s, or late orders are in the first i items. The count in a range is a difference of two prefix counts, just like a sum.
-
Prefix XOR. Let
px[i]be the XOR of the first i numbers. The XOR ofnums[i]up to (not including)nums[j]ispx[j] ^ px[i], because XORing a number twice cancels it out, so the shared part before i disappears. -
Prefix products. You'd like to divide two prefix products, but a single 0 makes that impossible, and some interview problems don't allow division at all. So to get the product of every number except the one at each index, multiply the product of everything before it (a prefix product) by the product of everything after it (a suffix product). That's our Product of All Other Numbers question.
-
Prefix sums of remainders. A subarray's sum is divisible by k exactly when the two prefix sums around it leave the same remainder when divided by k. Count remainders in a hash map, the same way as subarray sum equals k.
-
Prefix max and min. You can keep the largest value so far, but you can't "subtract" a maximum, so this only answers questions about prefixes, not about any range. For the maximum of any range, use a sparse table or a segment tree. For the maximum of a window that slides, use a monotonic deque.
Prefix Sums with Binary Search and Two Pointers
If every number is positive, the prefix sums only go up, so the prefix sum array is sorted. That opens up two more tools:
-
Binary search. "On which day did total sales first reach 10 cakes?" is the first j where
prefix[j]is at least 10. With the bakery's prefix sums [0, 4, 6, 13, 14, 19], that'sprefix[3]= 13, which counts days 0 through 2, so the answer is day 2. Binary search finds it in O(log n) time. The same idea picks a random item with probability proportional to its weight: choose a random number r from 0 up to (not including) the total weight, binary search for the first prefix sum bigger than r, and pick the item just before that position. -
Two pointers. A subarray adds up to k when
prefix[j] - prefix[i]= k, so with positive numbers you're looking for two items in a sorted array that differ by k. Two pointers that only move forward find them. In fact, that's what a sliding window is: two pointers moving forward over the prefix sums.
With negative numbers, the prefix sums go up and down, so neither trick works. That's when you need the hash map.
Prefix Sum Time and Space Complexity
| Operation | Time | Space |
|---|---|---|
| Build a prefix sum array | O(n) | O(n) |
| Sum of one range | O(1) | O(1) |
| Count subarrays that sum to k | O(n) on average (hash map lookups) | O(n) |
| Build a 2-D prefix sum table (m rows, n columns) | O(m · n) | O(m · n) |
| Sum of one rectangle | O(1) | O(1) |
| Difference array: one range update, then rebuild | O(1) per update, O(n) to rebuild | O(n) |
The catch: prefix sums are for data that doesn't change. If one number changes, every prefix sum after it changes too, and fixing them takes O(n) time. If updates and range sums are mixed together, use a Fenwick tree (binary indexed tree) or a segment tree, which do both in O(log n) time.
For more on how to count steps like this, see our big O notation guide.
Prefix Sums vs. Sliding Window vs. Kadane's Algorithm
All three handle questions about subarray sums. Here's which one to reach for:
| Problem | Best tool | Time | Extra space |
|---|---|---|---|
| Many range sums on data that doesn't change | Prefix sums | O(n) once, then O(1) per query | O(n) |
| Count or find subarrays that add up to k, negatives allowed | Prefix sums + hash map | O(n) | O(n) |
| Longest or shortest subarray with a sum limit, all numbers positive | Sliding window | O(n) | O(1) |
| Largest subarray sum | Kadane's algorithm | O(n) | O(1) |
| Many range updates, then read every value | Difference array | O(1) per update, O(n) at the end | O(n) |
Kadane's algorithm is closely related. The largest subarray sum is
the largest prefix[j] - prefix[i] with
i < j, so as you walk through
the prefix sums, subtract the smallest prefix sum you've seen so far
and keep the best difference. That's
Kadane's
algorithm seen through prefix sums, and like Kadane's, it only
needs O(1) extra space if you keep the
running sum instead of the whole
array.
Common Prefix Sum Mistakes
-
Off-by-one ranges. With the n + 1 convention, the sum of
nums[left]throughnums[right]isprefix[right + 1] - prefix[left]. Writingprefix[right] - prefix[left]leaves outnums[right]. -
Forgetting the {0: 1} entry. Without it, subarray sum equals k misses every subarray that starts at index 0.
-
Recording the running sum before looking it up. When k = 0, the current prefix sum then matches itself, and you count empty subarrays.
-
Overflow. The total of many numbers can be much bigger than any one of them. In Java and C++, store prefix sums in a
longorlong long, even if the input isints. -
Using a sliding window when numbers can be negative. Shrinking the window can throw away a start that would have worked later. Use prefix sums with a hash map.
-
Negative remainders. In Java, JavaScript, and C++,
-7 % 3is −1, not 2. When you group prefix sums by remainder, use((x % k) + k) % kso the same remainder always gets the same key. -
Rebuilding after every update. If the numbers change between queries, each change costs O(n) to fix. Use a Fenwick tree or segment tree instead.
Classic Prefix Sum Problems
- Range sum query on an array that doesn't change, and the 2-D version on a grid. Build once, answer each query in O(1).
-
Subarray sum equals k. Count
earlier prefix sums equal to
runningSum - kin a hash map. - Longest subarray with sum k. Store the first index where each prefix sum appears instead of a count.
- Subarray sums divisible by k. Count prefix sums by their remainder.
- Longest subarray with equal 0s and 1s. Count each 0 as −1, then find the longest subarray that adds up to 0.
- Pivot index (where the sum on the left equals the sum on the right). The right side is the total minus the left side minus the number at the pivot.
- Product of every other number. Prefix products times suffix products. Practice it: Product of All Other Numbers.
- Range additions, flight bookings, car pooling. Difference arrays.
- Random pick with weight. Prefix sums of the weights plus binary search.
- XOR of a subarray. Prefix XOR.
- Maximum subarray. Kadane's algorithm, or prefix sums minus the smallest earlier prefix sum.
Prefix Sum interview questions to practice
Each one walks you through a real coding interview problem one hint at a time.
Your first 3 questions are free. Just sign in, no credit card.
Interview coming up?
Get the free 7-day email crash course. You'll learn how to think algorithmically, so you can break down tricky coding interview questions.
No prior computer science training necessary—we'll get you up to speed quickly, skipping all the overly academic stuff.
No spam. One-click unsubscribe whenever.
You're in! Head over to your email inbox right now to read day one!
Interview Cake