Index Ai Academy
Glossary · Phase 7 · Software engineering

Prefix sum

Also written: prefix sums, running total, running totals

The total of everything up to each position, so any range's total is one subtraction.

The trail club has a counter at the trailhead that records hikers each day. "How many came between day 30 and day 90?" Adding up the range every time costs O(n) per question. Instead, build the running totals once: prefix[i] is the total of the first i days. Then any range total is one subtraction, prefix[b] - prefix[a].

Try it now

Most problems give themselves away: sorted input, a count, a range, or a fixed-size window.

Learn it properly

Patterns for coding problems · Two pointers, counting with dictionaries, prefix sums and sliding windows: O(n) answers to classic problems. About 45 minutes.

Create a free account See what's in the lesson

Other terms from the same lesson

Never trained an AI?

Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account.

Teach it to write