Dynamic Programming21 sections · 916 units
Open in Course

Prefix Sums - Implementation

The code

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 00-indexed, adjust the formula to pref[r+1]pref[l]pref[r+1] - pref[l]. Off-by-one errors are the most common bug here. Trace through a small example by hand before submitting.

Time complexity: O(n)O(n) to build, O(1)O(1) per query.

Space complexity: O(n)O(n) for the prefix array.