Prefix sums
A prefix-sum slice stores pref[i] = a[0] + ... + a[i-1]. Any subarray sum a[l] + ... + a[r-1] is then pref[r] - pref[l] in constant time after an O(n) preprocess.
Detailed Explanation
You will be asked many range sums on the same slice: totals for each day-range, each window of a report. Adding in a loop per query is O(n) per query. One forward pass builds prefixes; each query is two reads.
The off-by-one convention. pref has length n+1. pref[0] == 0. pref[i] is the sum of the first i elements. The sum of a[l:r] (Go half-open slice) is pref[r] - pref[l]. This matches slice indexes and avoids a special case at l == 0.
What you can put in pref. Integers, and with care floats (precision drifts). Counts (1 if a predicate holds). Xor prefixes (pref[r]^pref[l]) for xor-range queries. 2D prefixes exist for matrices: sum[i+1][j+1] = cell + above + left - corner.
Difference arrays are the inverse idea: to add v to a range [l, r) many times, add v at l and subtract v at r on a difference slice, then prefix-sum once to materialize.
Go types. Use int64 if the sum can exceed 32-bit int on a 32-bit build, or if you are summing large ints. Overflow wraps. For money, use integer cents, not float64.
What it costs. O(n) time and O(n) extra space for pref. Each query is O(1). If you only need one range, a loop is simpler. If you mutate a often, prefixes go stale; rebuild or use a Fenwick tree / segment tree (not in the standard library).
Code Examples
package main
import "fmt"
func prefixes(a []int) []int {
pref := make([]int, len(a)+1)
for i, v := range a {
pref[i+1] = pref[i] + v
}
return pref
}
func sum(pref []int, l, r int) int {
return pref[r] - pref[l] // a[l:r]
}
func main() {
p := prefixes([]int{2, 3, 1, 4})
fmt.Println(sum(p, 1, 3)) // 3+1 = 4
}func addRange(diff []int, l, r, v int) {
diff[l] += v
if r < len(diff) {
diff[r] -= v
}
}Common Gotchas
Using `pref[r] - pref[l-1]` with `l == 0` panics or reads the wrong cell
prefer length `n+1` and half-open indexes.
Integer overflow wraps
pick `int64` when the domain can exceed 2³¹-1 on 32-bit `int`.
Prefixes of a mutated slice are wrong until rebuilt
Prefixes of a mutated slice are wrong until rebuilt
`pref` includes a leading zero so `sum(0, n)` is `pref[n]`
`pref` includes a leading zero so `sum(0, n)` is `pref[n]`