Prefix sums
Beginner · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A prefix sum list stores the running total up to each position. Once built in one pass, the total of any stretch between two positions is just one subtraction, so you can answer thousands of range questions without adding up numbers again and again.
Practical use cases
- Web app: Sales between two dates on a dashboard. An analytics page lets the owner pick any date range and shows total sales. Adding up day by day for every pick is slow with years of data. Storing a running total per day lets the page subtract two numbers and answer instantly, however wide the range.
- Web app: Wallet or passbook balance on any day. A UPI-style passbook shows a running balance after every transaction. To show how much was spent between the 5th and the 20th, the app subtracts the balance on the 5th from the balance on the 20th. No need to add up each payment inside the range. The answer appears the moment the user picks the two dates.
- System: Image processing and reports. Blur and brightness tools over huge photos, and database reports that total many ranges, keep running totals so every region sum is a handful of subtractions instead of a long addition.
The story: The Chai Stall Ledger
Raju runs a chai stall near the bus stand and writes down every day's cups sold. His owner keeps asking questions: "How many cups did we sell between Tuesday and Friday?" "And from Monday to Thursday?" "And last week, days 3 to 6?"
Every time, Raju added the numbers up again, cup by cup. With 1,000 questions a month, his pencil went on strike.
Then Raju had an idea: add one extra column to the ledger called "total so far". Now, to find the cups between any two days, he just takes the "total so far" at the end day and subtracts the "total so far" from just before the start day. One subtraction, any question, instantly.
How to spot this problem, and where you need it
Users repeatedly ask for the total of a range inside the same list of numbers, and recalculating the sum from scratch for each question makes the page or report slow.
Signs you need it
- The same array is summed between different start and end positions many times, using a loop inside a loop.
- The problem statement says sum of elements from index i to j, with many queries.
- A dashboard date-range picker gets slower as the history grows, because it totals every day each time.
Where to use it in a project
- Analytics screens: sales, visits, signups or expenses between any two dates.
- Statistic pages such as cricket runs between overs, or running balances in banking and wallet apps.
The solution
Do the adding once. Make a second list where each position holds the total of everything up to and including it, building it in a single pass: previous total plus the new number. To find the sum from position i to position j, take the total at j and subtract the total just before i. Each question now costs a single subtraction.
Payoff: Before: adding up to 365 daily numbers for every range question. After: one pass to build, then every question is a single subtraction.
Explain it like I am 8
Imagine you are collecting stickers and you write your running total after each day. Want to know how many you got from day 3 to day 6? Look at the total on day 6, then take away the total from day 2. What is left is exactly what you collected in between.
How it works, step by step
- Build once. Make a new list where each spot holds the sum of everything up to that spot. Start with 0 in front.
- Answer many times. For days
ltor:prefix[r] - prefix[l - 1]. - Why it works. The total up to
rincludes everything beforeltoo. Subtracting removes that extra part. - Pay a little, save a lot. One O(n) pass up front turns every future question into O(1).
The code in four languages
PHP
<?php
// Build ONCE: prefix[i] = sum of the first i items
function buildPrefix(array $cups): array {
$prefix = [0]; // sum of nothing = 0
foreach ($cups as $i => $c) {
$prefix[$i + 1] = $prefix[$i] + $c;
}
return $prefix;
}
// Ask MANY times: days l..r (1-based, inclusive)
function rangeSum(array $prefix, int $l, int $r): int {
return $prefix[$r] - $prefix[$l - 1];
}
$cups = [3, 5, 2, 8, 1, 4, 6];
$prefix = buildPrefix($cups); // [0,3,8,10,18,19,23,29]
echo rangeSum($prefix, 3, 6); // 2+8+1+4 = 15JavaScript
// Build ONCE: prefix[i] = sum of the first i items
function buildPrefix(cups) {
const prefix = [0]; // sum of nothing = 0
cups.forEach((c, i) => { prefix[i + 1] = prefix[i] + c; });
return prefix;
}
// Ask MANY times: days l..r (1-based, inclusive)
const rangeSum = (prefix, l, r) => prefix[r] - prefix[l - 1];
const cups = [3, 5, 2, 8, 1, 4, 6];
const prefix = buildPrefix(cups); // [0,3,8,10,18,19,23,29]
console.log(rangeSum(prefix, 3, 6)); // 2+8+1+4 = 15Java
import java.util.*;
public class Main {
// Build ONCE: prefix[i] = sum of the first i items
static int[] buildPrefix(int[] cups) {
int[] prefix = new int[cups.length + 1]; // prefix[0] = 0: sum of nothing
for (int i = 0; i < cups.length; i++) {
prefix[i + 1] = prefix[i] + cups[i];
}
return prefix;
}
// Ask MANY times: days l..r (1-based, inclusive)
static int rangeSum(int[] prefix, int l, int r) {
return prefix[r] - prefix[l - 1];
}
public static void main(String[] args) {
int[] cups = {3, 5, 2, 8, 1, 4, 6};
int[] prefix = buildPrefix(cups); // [0,3,8,10,18,19,23,29]
System.out.println(Arrays.toString(prefix));
System.out.println(rangeSum(prefix, 3, 6)); // 2+8+1+4 = 15
}
}Go
package main
import "fmt"
// buildPrefix builds ONCE: prefix[i] = sum of the first i items.
func buildPrefix(cups []int) []int {
prefix := make([]int, len(cups)+1) // prefix[0] = 0: sum of nothing
for i, c := range cups {
prefix[i+1] = prefix[i] + c
}
return prefix
}
// rangeSum answers MANY times: days l..r (1-based, inclusive).
func rangeSum(prefix []int, l, r int) int {
return prefix[r] - prefix[l-1]
}
func main() {
cups := []int{3, 5, 2, 8, 1, 4, 6}
prefix := buildPrefix(cups)
fmt.Println(prefix) // [0 3 8 10 18 19 23 29]
fmt.Println(rangeSum(prefix, 3, 6)) // 2+8+1+4 = 15
}Time: Build O(n) · each query O(1) · Extra space: O(n). Great when you ask many range questions about data that does not change.
Watch out for
- Off-by-one errors. Keep the extra leading 0 so
l - 1never falls off the front. - Using it on data that keeps changing. Every update forces you to rebuild (see Fenwick trees later).
Quick check
- What does prefix[5] store?
- Only item 5
- Sum of the first 5 items
- Largest of 5 items
- How is a range sum from day l to r computed?
- prefix[r] + prefix[l]
- prefix[r] - prefix[l - 1]
- prefix[l] - prefix[r]
- After building, each range question costs…
- O(1)
- O(n)
- O(n²)