Dynamic Programming21 sections · 916 units
Open in Course

Static Range Sum Queries - Implementation

Complete solution

function solve(n, q, a)
    pref[0] := 0
    for i from 1 to n
        pref[i] := pref[i-1] + a[i]
    for each query (l, r)
        print pref[r] - pref[l-1]

In CSES problems, indices are typically 11-based. Using pref[0]=0pref[0] = 0 as a sentinel handles this cleanly. Build the prefix array in one pass, then answer each query with one subtraction.

Time complexity: O(n+q)O(n + q).

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