Prefix Sums: Compute Once, Answer Many Times
Picture a year of daily step counts, then a thousand questions like "how many steps from day 40 to day 200?". The direct way adds up every range again:
total := 0
for i := from; i <= to; i++ {
total += steps[i]
}
One question can take n steps, so q questions take up to n × q. With 100,000 days and 100,000 questions, that's 10 billion additions.
Keep a running total
A prefix sum stores the total of every value before each position:
xs: 4 8 3 7
p: 0 4 12 15 22
p[i] is the sum of xs[0:i], so p has one more value than xs and always starts with 0. Building it takes one pass:
p := make([]int, len(xs)+1)
for i, x := range xs {
p[i+1] = p[i] + x
}
Every range becomes one subtraction
The sum of xs[from] through xs[to] (both included) is everything before to + 1, minus everything before from:
sum := p[to+1] - p[from]
One O(n) pass to build it, then every question is O(1). That's the heart of choosing a data structure: do some work once up front, so the questions that repeat become cheap.
Watch out for off-by-one errors: puzzles often number days from 1, while Go indexes from 0. Convert in one place only, when reading the input, as main does in this lesson.
Task
- Complete
prefixSums(xs []int) []int: a slice of lengthlen(xs)+1withp[i]= the sum ofxs[0:i]. For an empty slice, the result is[0]. - Complete
rangeSum(p []int, from, to int) int: the sum ofxs[from]throughxs[to], both included, with one subtraction fromp.
main already reads the step log and the range questions from the input.