function buildPrefix(a, n)
pref[0] := 0
for i from 1 to n
pref[i] := pref[i-1] + a[i]
return pref
function rangeSum(pref, l, r)
return pref[r] - pref[l-1]
Watch the indexing. If your array is -indexed, adjust the formula to . Off-by-one errors are the most common bug here. Trace through a small example by hand before submitting.
Time complexity: to build, per query.
Space complexity: for the prefix array.