Dynamic Programming21 sections · 916 units
Open in Course

Static Range Sum Queries - Walkthrough

Applying prefix sums

Problem: given array and queries (l,r)(l, r), answer each query with sum of arr[l..r]arr[l..r]. Precompute prefix sums in O(n)O(n). For each query, return prefix[r+1]prefix[l]prefix[r+1] - prefix[l] in O(1)O(1).

Example: arr=[1,2,3,4,5]arr = [1, 2, 3, 4, 5], queries [(0,2),(1,4),(2,3)][(0, 2), (1, 4), (2, 3)]. Prefix: [0,1,3,6,10,15][0, 1, 3, 6, 10, 15]. Answers: prefix[3]prefix[0]=6prefix[3] - prefix[0] = 6, prefix[5]prefix[1]=14prefix[5] - prefix[1] = 14, prefix[4]prefix[2]=7prefix[4] - prefix[2] = 7. The pattern generalizes to any associative operation with an inverse, like XOR or modular addition.