Prefix sum
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A prefix sum is a running total saved at every position, so the total of any stretch is just one subtraction of two saved numbers. You do the adding once and reuse it for every question.
Practical use cases
- Web app: Bank passbook for any date range. A banking app lets users pick two dates and shows total spent between them. Adding 20,000 transactions on every request is slow. With a saved running balance after each transaction, the total is the balance at the end minus the balance at the start. The user picks dates and the total appears immediately, however long the account history is.
- Web app: Sales report for any week. An admin dashboard lets managers drag over a chart to total sales for a custom range. With running totals saved in advance, every drag is answered with one subtraction, so the page stays smooth.
- Web app: Cricket stats between two matches. A fantasy cricket site shows a player's runs from match 12 to match 40. Running totals built once give the answer with one subtraction, so each stats page loads instantly however many users ask.
- System: Image processing and database analytics. Blur filters and heatmap tools use running totals in two dimensions to get any rectangle's total instantly. Pictures blur quickly because the adding was done in advance.
The story: The Kirana Ledger Trick
Raju kept a daily profit book for his chai stall, with some bad days where he lost money. One evening a customer, a retired accountant, asked: "In how many different stretches of days did you make exactly 7 rupees of profit?" Raju gulped. A stretch can start and end on any day!
He began adding: day 1 to 2, day 1 to 3, day 1 to 4... then day 2 to 2, day 2 to 3... His book had 300 days, and the pencil snapped. Mira peeked and said, "Keep one more column: the total so far. The profit from day 5 to day 9 is just (total up to day 9) minus (total up to day 4)."
That is the whole smell. When a problem asks about sums of ranges or subarrays adding up to a target, a subtraction of two running totals gives any range instantly. Better still: instead of testing every start day, ask "have I seen the running total that is exactly 7 less than today's?" A notebook (hash map) of earlier totals answers that in a blink.
That is prefix sum. Build the running totals once, and every range question becomes a single subtraction.
How to spot this problem, and where you need it
Many users keep asking for the total (or count) of a stretch of data that does not change often, and you re-add the same numbers over and over.
Signs you need it
- You have a loop that sums a range inside a function called many times with different start and end values.
- Pages that show "total between date A and date B" get slower as history grows.
- The wording is "sum of subarray", "number of ... between index i and j", or "how many in range".
Where to use it in a project
- Statements, ledgers and passbooks with a "from date to date" filter.
- Dashboard charts with draggable ranges that show a total for the selected stretch.
- Counting events or flags between two positions in a large list.
The solution
Make one pass and store a running total at each position: total after 1 item, after 2, and so on, starting with a zero at the front. To get the sum from item i to item j, take the running total at j and subtract the running total just before i. Build once, then every question costs a single subtraction.
Payoff: Before: adding up to 20,000 numbers per request. After: one subtraction.
Explain it like I am 8
You walk along a road with milestones that say how many kilometres you have walked. To know how far it is from the 4th stone to the 9th, you do not walk it again. You just subtract the two stone numbers.
How it works, step by step
- Clues: "sum of a range", "subarray sum equals k", "many queries on the same array". Think prefix sum.
- Running total:
prefix[i] = prefix[i-1] + a[i], with a starting total of 0 before the first element. - Any range sum from
j+1toiisprefix[i] - prefix[j]. Two lookups, no loop. - For "sum equals k": at each step, a good stretch ends here if the total
prefix - kwas seen earlier. Look that up in a map of counts. - Remember to store the starting 0 in the map, so stretches that start at day 0 are counted.
The code in four languages
PHP
<?php
// Subarray Sum Equals K: count stretches whose total is exactly k
function countSubarrays(array $nums, int $k): int {
$seen = [0 => 1]; // running total => how many times seen (0 before we start)
$prefix = 0;
$count = 0;
foreach ($nums as $x) {
$prefix += $x; // running total up to today
$need = $prefix - $k; // earlier total that makes a stretch of sum k
if (isset($seen[$need])) {
$count += $seen[$need]; // each earlier copy is one stretch
}
$seen[$prefix] = ($seen[$prefix] ?? 0) + 1;
}
return $count;
}
echo countSubarrays([3, 4, 7, 2, -3, 1, 4, 2], 7); // 4JavaScript
// Subarray Sum Equals K: count stretches whose total is exactly k
function countSubarrays(nums, k) {
const seen = new Map([[0, 1]]); // running total -> how many times seen (0 before we start)
let prefix = 0;
let count = 0;
for (const x of nums) {
prefix += x; // running total up to today
const need = prefix - k; // earlier total that makes a stretch of sum k
if (seen.has(need)) {
count += seen.get(need); // each earlier copy is one stretch
}
seen.set(prefix, (seen.get(prefix) || 0) + 1);
}
return count;
}
console.log(countSubarrays([3, 4, 7, 2, -3, 1, 4, 2], 7)); // 4Java
import java.util.*;
public class Main {
// Subarray Sum Equals K: count stretches whose total is exactly k
static int countSubarrays(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>();
seen.put(0, 1); // running total -> how many times seen (0 before we start)
int prefix = 0;
int count = 0;
for (int x : nums) {
prefix += x; // running total up to today
int need = prefix - k; // earlier total that makes a stretch of sum k
if (seen.containsKey(need)) {
count += seen.get(need); // each earlier copy is one stretch
}
seen.merge(prefix, 1, Integer::sum);
}
return count;
}
public static void main(String[] args) {
System.out.println(countSubarrays(new int[]{3, 4, 7, 2, -3, 1, 4, 2}, 7)); // 4
}
}Go
package main
import "fmt"
// countSubarrays counts stretches whose total is exactly k.
func countSubarrays(nums []int, k int) int {
seen := map[int]int{0: 1} // running total -> how many times seen (0 before we start)
prefix, count := 0, 0
for _, x := range nums {
prefix += x // running total up to today
need := prefix - k // earlier total that makes a stretch of sum k
count += seen[need] // each earlier copy is one stretch (a missing key gives 0)
seen[prefix]++
}
return count
}
func main() {
fmt.Println(countSubarrays([]int{3, 4, 7, 2, -3, 1, 4, 2}, 7)) // 4
}Time: O(n) · Extra space: O(n). One pass with constant-time map lookups; the map may hold one total per day.
Watch out for
- Forgetting to put
0(count 1) in the map first, which loses stretches that start at the very first element. - Updating the map before looking up
prefix - k. When k is 0 you would count an empty stretch. - Trying a sliding window when the array has negative numbers. A window only works if sums grow predictably; prefix sums do not care.
Quick check
- Sum of elements from index j+1 to i using a prefix array?
- prefix[i] + prefix[j]
- prefix[i] - prefix[j]
- prefix[j] - prefix[i]
- Which clue points to prefix sum?
- "Largest value in a window"
- "Find the middle node"
- "Many range-sum queries on a fixed array"
- Why do we store the total 0 in the map at the start?
- So stretches beginning at index 0 are counted
- To avoid a crash
- To sort the totals