Prefix sums turn repeated range totals into two lookups

← Back to Blog & Articles

A prefix-sum array stores cumulative totals so that the sum of a contiguous range can be recovered by subtraction. It is useful when the same unchanged data will receive many range-sum queries.

Worked example

For values 3, 1, 4, and 2, build cumulative totals 0, 3, 4, 8, and 10. The total for positions 1 through 2, using zero-based positions, is cumulative[3] minus cumulative[1], or 8 minus 3, which equals 5. The leading zero lets ranges starting at the first position use the same rule.

What to check

Write the endpoint convention down. A half-open range from l to r includes l and excludes r, so its total is prefix[r] minus prefix[l]. Building the prefix array takes linear time and extra storage. Each later query takes constant time. Updating one original value requires additional work in this representation, which makes a different data structure useful when updates are frequent.

Continue with the book

Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.


Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.

Scroll to Top