Computing a Sequence of Prefix Totals
A prefix scan emits the accumulator after each input so later code can inspect cumulative work.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Follow four values
For daily changes 2, minus 1, 4, and 3, running totals after the days are 2, 1, 5, and 8. A one-time sum produces only eight. The same accumulator update powers both results.
Include a starting point when useful
Adding an initial zero gives the total before the first day and makes a range sum a difference of two stored prefixes. From changes with offsets one through two, subtract prefix 1 from prefix 3 to get 3. Half-open boundaries help specify which terms those two prefixes cover.[1]
Retain a sum at every boundary
Given values 3, minus 2, 4, and 6, start a prefix table at zero. The next entries are 3, 1, 5, and 11. Entry \(P_j\) is the sum of exactly the first \(j\) values. This makes the sum over offsets \([1,3)\) equal to \(P_3-P_1=5-3=2\). It includes minus two and four. The initial zero makes a range from zero use the same subtraction rule. See range-sum lookups.
Choose how much of the output to retain
If a dashboard only needs the current running total, it can emit each prefix without keeping the whole table. If callers need arbitrary range queries later, retain the boundaries. An update to an early input can change several later prefix values, so treat this as a construction for static inputs unless there is a suitable update strategy.
Try an empty range with identical endpoints. Subtracting the same prefix returns zero. A full range uses entries at its two outer boundaries. Verify both and use different negative and positive terms where a mistaken end index would be visible. Half-open slices gives the index convention.