Using Prefix Totals for Range Sums

An array of accumulated totals can answer an unchanged sequence's range sums using two array reads and a subtraction.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Build the prefix values
  2. Recognize the update cost
  3. Derive one query from the two stored boundaries
  4. Reconsider the structure when cells change often

Build the prefix values

For 3, minus 1, and 5, store 0, 3, 2, 7. For offsets \([1,3)\), subtract prefix one from prefix three to get 4. Prefix scans explain how to build this table in one traversal.

Recognize the update cost

Changing the first value changes every later prefix. If arbitrary updates and range queries are both important, use a data structure designed for both. See Fenwick trees for supporting prefix queries with local updates.[1]

Derive one query from the two stored boundaries

For values [8, -3, 4, 6], store a leading zero followed by cumulative sums. The sum on \([1,3)\) equals the cumulative total ending at boundary three minus the total ending at boundary one. This removes exactly the prefix outside the queried range. See prefix total scans.

Boundary     0  1  2  3   4
Prefix sum   0  8  5  9  15
Sum [1,3) = 9 - 8 = 1, matching -3 + 4
Sum [2,2) = 5 - 5 = 0

Reconsider the structure when cells change often

A point update affects every later cumulative total. Pure prefix sums work well on a static snapshot with many reads. With frequent mutations, a tree of partial sums can localize updates. Test negative values because cumulative totals need not be monotonic.

References

  1. Jeff Erickson, Algorithms ↩