1D prefix sum
Beginner · 7 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 every position. Any "sum between position a and position b" is then the total at b minus the total just before a, so one subtraction replaces a whole loop.
Practical use cases
- Web app: Sales between two dates on a dashboard. An admin picks any date range on a report and the page shows total sales. Instead of adding up 90 daily numbers for each pick, the app keeps running totals once and subtracts two of them, so changing the date picker feels instant even over years of data.
- Web app: Bank passbook balance between dates. A UPI or banking statement page shows total credits between the 5th and the 20th. With a running total per day, the answer is one subtraction rather than reading every transaction in the range. Customers get their answer at once, and the bank server avoids reading thousands of rows for every statement request.
- System: SQL window functions and scoreboards. Running totals in SQL (SUM OVER) and runs-between-overs in a cricket scoreboard use the same cumulative idea, which databases and apps rely on for fast reports. Reports on huge tables stay fast, because the running total is prepared once and reused by every range question.
The story: Grandpa Bhaskar's Passbook
Grandpa Bhaskar goes to the bank every month and gets his passbook printed. Each line shows what he put in, and, on the right, the balance so far. Mira loves reading it like a storybook.
One evening Kabir asked, "Grandpa, how much did you save between March and June?" Grandpa put on his glasses and began adding the March, April, May and June lines one by one. Then Zoya asked about February to August. Then Aarav asked about a different stretch. Grandpa sighed: "Every question, I add again from scratch!"
Mira picked up the passbook. "Grandpa, you do not have to add anything. The balance column already holds the running total. Take the balance after June and subtract the balance before March. Whatever is left is exactly what came in between." Grandpa tried it and chuckled. That running-total column is called a prefix sum, the same trick Raju used for his chai ledger, now with one tiny upgrade: a leading zero.
How to spot this problem, and where you need it
Users keep asking for the total of a stretch of numbers, and looping over the stretch each time becomes slow as data and requests grow.
Signs you need it
- The feature is "sum between two points" (dates, positions, overs) asked many times over the same data.
- Your code has a for-loop that adds items from index a to b inside another loop over many queries.
- The data itself does not change between queries, or changes rarely.
- The problem says "range sum" or "subarray sum" with many queries.
Where to use it in a project
- Reporting dashboards with date pickers: sales, signups, visits, expenses.
- Statement and passbook pages that total entries in a chosen period.
The solution
Build one list where position i holds the sum of everything from the start up to i. Do this once in a single pass. To get the sum from a to b, take the value at b and subtract the value just before a. Each question now costs one subtraction, however long the range.
Payoff: Before: adding up to 365 numbers per question. After: one subtraction, so a year-long range is as fast as a one-day range.
Explain it like I am 8
Imagine a staircase where each step has a number painted on it: how many stickers you have collected up to that step. To know how many you got between step 3 and step 6, look at the number on step 6 and take away the number on step 2. The stickers on the lower steps are the ones you take away.
How it works, step by step
- Start with a zero. Make a new list whose first spot is 0, meaning "nothing added yet".
- Build once. For every item, new spot = previous spot + this item. One pass over the data.
- Ask a range (l to r, counting from 0). The answer is
prefix[r + 1] - prefix[l]. - Why the shift by one?
prefix[k]means "the first k items", so it stops just before item k. - Remember the limit: it is perfect while the numbers never change. If one number changes, many balances go stale.
The code in four languages
PHP
<?php
// Build ONCE. prefix[i] = sum of the first i items (prefix[0] = 0)
function buildPrefix(array $a): array {
$prefix = [0];
foreach ($a as $i => $v) {
$prefix[] = $prefix[$i] + $v; // old balance + this week
}
return $prefix;
}
// Ask MANY times. l and r are 0-based and inclusive
function rangeSum(array $prefix, int $l, int $r): int {
return $prefix[$r + 1] - $prefix[$l];
}
$saved = [4, 2, 7, 1, 3, 5, 6];
$prefix = buildPrefix($saved);
echo implode(',', $prefix) . PHP_EOL; // 0,4,6,13,14,17,22,28
echo rangeSum($prefix, 2, 5) . PHP_EOL; // 7+1+3+5 = 16
echo rangeSum($prefix, 0, 3) . PHP_EOL; // 4+2+7+1 = 14JavaScript
// Build ONCE. prefix[i] = sum of the first i items (prefix[0] = 0)
function buildPrefix(a) {
const prefix = [0];
a.forEach((v, i) => prefix.push(prefix[i] + v)); // old balance + this week
return prefix;
}
// Ask MANY times. l and r are 0-based and inclusive
function rangeSum(prefix, l, r) {
return prefix[r + 1] - prefix[l];
}
const saved = [4, 2, 7, 1, 3, 5, 6];
const prefix = buildPrefix(saved);
console.log(prefix.join(',')); // 0,4,6,13,14,17,22,28
console.log(rangeSum(prefix, 2, 5)); // 7+1+3+5 = 16
console.log(rangeSum(prefix, 0, 3)); // 4+2+7+1 = 14Java
import java.util.*;
import java.util.stream.*;
public class Main {
// Build ONCE. prefix[i] = sum of the first i items (prefix[0] = 0)
static int[] buildPrefix(int[] a) {
int[] prefix = new int[a.length + 1];
for (int i = 0; i < a.length; i++) {
prefix[i + 1] = prefix[i] + a[i]; // old balance + this week
}
return prefix;
}
// Ask MANY times. l and r are 0-based and inclusive
static int rangeSum(int[] prefix, int l, int r) {
return prefix[r + 1] - prefix[l];
}
public static void main(String[] args) {
int[] saved = {4, 2, 7, 1, 3, 5, 6};
int[] prefix = buildPrefix(saved);
System.out.println(Arrays.stream(prefix).mapToObj(String::valueOf).collect(Collectors.joining(","))); // 0,4,6,13,14,17,22,28
System.out.println(rangeSum(prefix, 2, 5)); // 7+1+3+5 = 16
System.out.println(rangeSum(prefix, 0, 3)); // 4+2+7+1 = 14
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// buildPrefix: build ONCE. prefix[i] = sum of the first i items (prefix[0] = 0).
func buildPrefix(a []int) []int {
prefix := []int{0}
for i, v := range a {
prefix = append(prefix, prefix[i]+v) // old balance + this week
}
return prefix
}
// rangeSum: ask MANY times. l and r are 0-based and inclusive.
func rangeSum(prefix []int, l, r int) int {
return prefix[r+1] - prefix[l]
}
func main() {
saved := []int{4, 2, 7, 1, 3, 5, 6}
prefix := buildPrefix(saved)
parts := make([]string, len(prefix))
for i, v := range prefix {
parts[i] = strconv.Itoa(v)
}
fmt.Println(strings.Join(parts, ",")) // 0,4,6,13,14,17,22,28
fmt.Println(rangeSum(prefix, 2, 5)) // 7+1+3+5 = 16
fmt.Println(rangeSum(prefix, 0, 3)) // 4+2+7+1 = 14
}Time: Build O(n), each query O(1) · Extra space: O(n). One pass up front makes every later range question a single subtraction, as long as the data never changes.
Watch out for
- Forgetting the leading 0, then crashing or giving a wrong answer when the range starts at the very first item.
- Mixing up the shift: with 0-based items and a leading 0, the answer is
prefix[r + 1] - prefix[l], notprefix[r] - prefix[l]. - Using it when numbers change often: each change makes every later balance wrong.
Quick check
- With a leading 0 and 0-based items, what is the sum of items l to r?
- prefix[r] - prefix[l]
- prefix[r + 1] - prefix[l]
- prefix[r] - prefix[l - 1]
- How long does one range question take once the prefix list is built?
- As long as the range is wide
- Proportional to the whole list
- One subtraction, constant time
- What is the main weakness of a plain prefix sum?
- It needs sorted data
- It goes stale when a value changes
- It cannot handle negative numbers