Answer many range-sum queries in constant time with prefix sums
Why it matters Prefix sums power fast range queries in sequence packing, cumulative metrics and attention implementations.
Packing and chunking code often asks 'how many tokens are in documents s to e?' thousands of times. A prefix sum array answers each query with one subtraction.
Write range_sums(x, starts, ends). x is a 1D array; starts and ends are int arrays of the same length with 0 <= s <= e <= len(x). Return an array where entry i is the sum of x[starts[i]:ends[i]] (half open, so s == e gives 0). Use prefix sums, no Python loop over queries.
def range_sums(x, starts, ends)Example
range_sums([3, 1, 4, 1, 5], [0, 1, 2], [2, 4, 2]) is [4, 6, 0].
Understand the idea
A prefix sum array stores running totals: c[k] = x[0] + ... + x[k-1], with c[0] = 0. Any range sum is then the difference of two prefix sums, like reading two odometer values and subtracting.
Worked example: x = [3, 1, 4, 1, 5]. c = [0, 3, 4, 8, 9, 14]. The sum of x[1:4] = 1 + 4 + 1 = 6, and c[4] - c[1] = 9 - 3 = 6. An empty range x[2:2] gives c[2] - c[2] = 0.
Rule: sum(x[s:e]) = c[e] - c[s], where c = concat([0], cumsum(x)). Building c costs O(N); each query costs O(1).
Packing code uses document offsets this way, and cumulative token counts make context window checks instant.
Shapes and data flow
x (N,) -> c (N + 1,); starts, ends (Q,) -> sums (Q,)