Prefix sum Created 2026-09-24 Updated 2026-10-14
A prefix sum stores the accumulated sum through a specified position in a finite sequence or array. For inputs , include the empty sum and set
For the original input , the prefix array including is . A negative entry makes the accumulated sum decrease; a prefix sum does not have to be monotone. Conversely, the original entry is recovered by subtraction: .
The useful cancellation is that any contiguous block has sum
Both prefixes include the entries before ; subtracting cancels those entries. In the example, the sum from positions two through four is , recovered as . The arithmetic mean of that block is , obtained by dividing its sum by its length. Prefix sums therefore make many repeated questions about an unchanged array cheap: reuse accumulated totals instead of resumming every block.
Figure 1.
Two prefix sums recover a contiguous block by subtraction
. The original six-entry array has negative as well as positive values. Highlighted entries two through four sum to two. Their accumulated endpoint values are and , so . The initial also handles a block beginning at the first entry without a separate arithmetic rule. Details.
The sequential recurrence builds all prefixes in time complexity and storage; each block query needs two reads and one subtraction, hence time complexity. These counts assume constant-cost arithmetic and access to array entries. If one input changes, all later stored prefixes change, so this simple representation is most useful when queries outnumber updates. For integer inputs, sufficient numeric capacity must be retained; with floating-point arithmetic, subtracting large nearby prefixes can lose relative accuracy for a small block total. The exact mathematical identity does not eliminate representation error.
The apparently sequential recurrence also motivates a prefix scan: associativity permits a tree of partial calculations that yields all accumulated results in parallel. Guy E. Blelloch's 1990 technical report systematically develops this operation and its applications; its authored chapter version explains the two tree sweeps used to obtain all prefixes. [ref]. [ref].