Math Fundamentals18 sections · 814 units
Open in Course

Range Sum - Prefix Sum Idea

Precompute cumulative sums

Create an array prefixprefix where prefix[i]prefix[i] is the sum of all elements from index 00 to ii. This is a cumulative sum.

For nums=[2,0,3,5,2,1]nums = [-2, 0, 3, -5, 2, -1], compute prefix=[2,2,1,4,2,3]prefix = [-2, -2, 1, -4, -2, -3]. Each entry adds the current element to the previous sum.

To find the sum from ii to jj, compute prefix[j]prefix[i1]prefix[j] - prefix[i-1] (or just prefix[j]prefix[j] if i=0i = 0). This uses the telescoping property: intermediate terms cancel.