Answer Interval Queries with Prefix Sums
Core idea
A prefix sum array p stores p[0]=0 and p[i] equal to the sum of the first i values. The sum of a half-open interval [left,right) is p[right]-p[left]. Building p takes O(n) time and space; each valid query takes O(1) under bounded-size arithmetic.
def build_prefix(values): p = [0] for value in values: p.append(p[-1] + value) return pprint(build_prefix([5,-2,4]))The initial zero supports intervals that start at index zero.
Query several intervals
def build_prefix(values): p = [0] for value in values: p.append(p[-1] + value) return pp = build_prefix([5,-2,4])for left,right in [(0,3),(1,3),(2,2)]: print(p[right]-p[left])Subtracting cancels the shared prefix. An empty interval sums to zero.
Common mistake
Require 0 <= left <= right <= n. If the input changes, old prefix sums can become stale. Inclusive right endpoints require a different index conversion.
Practice
Build a prefix table and answer several half-open interval queries; include an empty interval and an interval ending at n.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Prefix sum queries
Check your understanding of prefix sums.
What is printed?
def build_prefix(values): p = [0] for value in values: p.append(p[-1] + value) return pp=build_prefix([2,5,1])print(p[3]-p[1])What is printed?
def build_prefix(values): p = [0] for value in values: p.append(p[-1] + value) return pprint(build_prefix([]))How is [l,r) summed?
When must a cached prefix table be rebuilt or updated?