awelgorithms

Exclusive-end range is prefix[R) minus prefix[L)

Updated

Leading-zero P[0]=0, P[i+1]=P[i]+a[i]. Half-open [L, R) covers L..R-1 and equals P[R] − P[L]. R is a fence, not a kept index.

What to focus on

Length of the range is R−L. [i, i) is empty and sums to 0. [0, n) is the whole array.

Worked examples

drop the last

a = [4, 1, 9], P = [0, 4, 5, 14], [0, 2)
  1. P[2]-P[0] = 5

Result: covers indices 0,1 → 4+1

keep last two

a = [4, 1, 9], P = [0, 4, 5, 14], [1, 3)
  1. P[3]-P[1] = 14-4 = 10

Result: covers 1,2 → 1+9

whole as [0,n)

a = [4, 1, 9], P = [0, 4, 5, 14], [0, 3)
  1. P[3]-P[0] = 14

Result: 4+1+9 = 14

Try it

Write rangeSum(P, L, R). P is a leading-zero prefix table. L is the inclusive left index. R is the exclusive right index. P[i] covers a[0..i). Return P[R] − P[L]. P of [4, 1, 9] [0, 2) → indices 0,1 sum 5 P of [4, 1, 9] [1, 3) → indices 1,2 sum 10 P of [4, 1, 9] [0, 3) → 14

a is a non-empty array of integers. Leading-zero P. 0 ≤ L ≤ R ≤ n. P[i] covers a[0..i).