Prefix sums and the running-sum map
1 A running total answers range questions
A shop writes down its profit at the end of each day, in thousands of rupees. A loss is a negative number. Over six days, the book reads:
The owner asks how much the shop made from day 1 to day 3. A loop adds 3 + (−1) + 1 and gets 3. One question like that is cheap. But a problem can ask 10⁵ such questions about 10⁵ days, and each one can cover most of the days. That is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
A shopkeeper would not add the days up again for every question. They keep a second column in the book: the total made so far. By the end of day 3, the total is 5. By the end of day 0, it was 2. Days 1 to 3 made the difference, 5 − 2 = 3. That is one subtraction, however many days the range covers.
That running total is a prefix sum. In code, the days are an array nums, and a range of days is a subarray: values that sit next to each other.
2 The prefix array
We keep the running totals in an array prefix with one more place than nums. prefix[i] is the total of everything before index i:
prefix[0]is 0, the total before day 0. This is the leading 0.- Each next place adds one day:
prefix[i + 1] = prefix[i] + nums[i].
Drawn as bars, the prefix array is the shop's total over time. Bar i is the total just before day i, and bar 6 is the total after the last day:
Each bar is a moment between two days, not a day itself. The rest of the lesson reads everything off this picture.
3 Any range in one subtraction
The sum of days 1 to 3 comes from two prefix values. The steps below show how:
On the bars, the same subtraction is the gap between bar 1 and bar 4:
The same holds for any range from l to r:
The r + 1 is where most off-by-one mistakes come from. prefix[i] stops just before index i, so to include index r we need prefix[r + 1]. prefix[l] also stops just before l, so it takes away everything before the range and nothing inside it.
The leading 0 covers ranges that start at index 0. Days 0 to 2 made prefix[3] − prefix[0] = 4 − 0 = 4. Without the leading 0, l = 0 would need its own if.
Building the array is one pass, O(n). Each range after that is one subtraction, O(1). So 10⁵ ranges over 10⁵ values take around 2 × 10⁵ steps instead of 10¹⁰. The array takes O(n) extra space.
4 Counting subarrays with sum k
The next question is harder: how many subarrays have sum exactly k? The owner asks it as: in how many stretches of days did we make exactly 5? Trying every start and every end is about n² pairs. At n = 10⁵ that is 10¹⁰ again, and TLE.
The bars turn this into something we can see. Days l to j made 5 exactly when bar j + 1 stands 5 above bar l. So we need pairs of bars where the later one is 5 higher. Our example has four:
Now we turn it around. We stand on one bar and look back: how many earlier bars are exactly k lower? Bar 6 is at 10, so it needs bars at 5. Bars 2 and 4 are both at 5, so bar 6 ends two stretches. We do not need to know where those bars are. We only need to know how many of them sit at 5.
A map gives that count in one step. Its keys are the running totals seen so far, and its values are how many bars had each total. This is the running-sum map, and we call it seen. One pass from left to right is enough, with a variable total as the current bar. We no longer need the prefix array.
Before the loop, seen holds {0: 1}. That entry is bar 0, the leading 0. Without it, the stretches that start on day 0 have no bar to look back to.
5 Tracing the map
At each index j, we do three things, in this order:
- Add
nums[j]tototal. - Look up
total − kinseen, and add its count tocount. - Add 1 to the count of
totalinseen.
Here is the run with k = 5. In the map, blue marks the total we looked up and found, and orange marks the total we just added:
The same run as a table:
| j | nums[j] | total | need = total − k | seen[need] | count |
|---|---|---|---|---|---|
| 0 | 2 | 2 | −3 | 0 | 0 |
| 1 | 3 | 5 | 0 | 1 | 1 |
| 2 | −1 | 4 | −1 | 0 | 1 |
| 3 | 1 | 5 | 0 | 1 | 2 |
| 4 | 3 | 8 | 3 | 0 | 2 |
| 5 | 2 | 10 | 5 | 2 | 4 |
The last row is the one the map is for. The total 5 came up twice before, so seen[5] is 2, and one lookup counts both stretches. A set of totals would only say "seen" and count 1. So the map keeps a count.
This is one pass, and each map step is O(1) on average, so the whole count is O(n). The map can hold up to n + 1 different totals, so it takes O(n) space.
6 Negative values: why a window fails here
The map never assumes the bars only go up. The loss on day 2 made bar 3 lower than bar 2, and the lookups did not mind. That matters, because the obvious faster idea does mind.
A later lesson teaches the sliding window. The window grows on the right, and shrinks from the left while its sum is too big. It works only when every value is positive. Then growing the window always raises the sum, and shrinking always lowers it.
A negative value breaks that. Take [1, 5, −3] with k = 2:
- The window takes 1, then 5. Its sum is 6, more than 2.
- It drops 1, and the sum is 5. That is still more than 2, so it drops 5 too.
- The window is empty when −3 arrives, and its sum is −3.
The window never sees [5, −3], whose sum is 2. It threw 5 away before the −3 could bring the sum back down.
The map finds it. The totals are 0, 1, 6 and 3. At the total 3, it needs 3 − 2 = 1, and bar 1 is at 1.
7 Mistakes and edge cases
- Off by one in the formula. prefix[r] − prefix[l] leaves out
nums[r]. For l = 1 and r = 3 it gives 4 − 2 = 2 instead of 3. - Forgetting
{0: 1}. On our example, the count comes out as 2. It misses [2, 3] and [2, 3, −1, 1], the subarrays that start at index 0. - Adding to the map before the lookup. Then the lookup can find the current prefix itself, which counts an empty subarray. On
[1, 2]with k = 0 the answer is 0, but this order gives 2. - Overflow. With 10⁵ values of 10⁹ each, the total reaches 10¹⁴. A 32-bit
intholds only about 2 × 10⁹. The count can overflow too: in an array of 10⁵ zeros with k = 0, every subarray counts, and there are about 5 × 10⁹ of them.
C++
Use long long for prefix, total, the map's keys and count. An int sum past 2 × 10⁹ wraps around to a wrong value without any error.
Use long, and Long keys. An int sum wraps around without any error. The map must be Map<Long, Long>, because total - k is a long, and a lookup with an int would never match a Long key.
Nothing to do. Python's integers grow as needed, so 10¹⁴ and 5 × 10⁹ are fine.
Nothing to do here. Numbers stay exact up to about 9 × 10¹⁵, so a total of 10¹⁴ is safe.
int is 64 bits on today's machines, so a total of 10¹⁴ fits. The count is an int64, as the problem asks.
Convert before adding. Write num as i64 before adding to total. An i32 sum past 2 × 10⁹ overflows.
Use long for prefix, total, the map's keys and count. An int sum past 2 × 10⁹ wraps around to a wrong value without any error.
8 When to use prefix sums
The sign is a question about the sum of a subarray, where adding up each range again would be too slow. Two shapes come up:
- Many range sums on an array that does not change. Build the prefix array once, then answer each range with one subtraction.
- Count or find subarrays with a given sum, with negatives allowed. Use the running-sum map.
The map idea bends to fit the question:
- The longest subarray with sum k. Store each sum's first index instead of a count.
- Sums divisible by k. Store each total's remainder by k. Two prefixes with the same remainder enclose a sum divisible by k.
- XOR instead of sum. XOR undoes itself, so a running XOR works the same way.
- A grid. A 2D prefix array holds the sum of the rectangle from the top-left corner to each cell.
The next lesson flips the idea around. A difference array handles many updates to ranges, where this lesson handled many questions about them.
Practice it
- Product of Array Except SelfMedium
- Subarray Sum Equals KMedium
- Maximum Size Subarray Sum Equals kMedium
- Range Sum Query - ImmutableEasy
- Range Sum Query 2D - ImmutableMedium
- Contiguous ArrayMedium
- Subarray Sums Divisible by KMedium
- Continuous Subarray SumMedium
- Longest subarray with sum 0Medium
- Count subarrays with given xor KMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.