Data Structures19 sections · 729 units
Open in Course

Range Sum - Answering Queries

Constant time lookup

Once you have the prefix array, queries are trivial:

function sumRange(left, right):
    return prefix[right + 1] - prefix[left]

Time: O(1)O(1). Space: O(1)O(1) per query. The +1+1 offset handles the convention that prefix[i]prefix[i] is the sum of elements before index ii. If this feels awkward, trace through an example until it clicks.