Dynamic Programming21 sections · 916 units
Open in Course

Static Range Sum Queries - Why Prefix Sums

Applying the technique

Build a prefix sum array where prefix[i] = sum of elements from index 1 to i. This takes O(n)O(n) time once. Now any range sum [a,b] = prefix[b] - prefix[a-1].

Why? prefix[b] includes everything up to b. Subtracting prefix[a-1] removes everything before a. You've converted q queries of O(n)O(n) each into q queries of O(1)O(1) each. Total: O(n+q)O(n + q) instead of O(n×q)O(n \times q).