Dynamic Programming21 sections · 916 units
Open in Course

Answering Range Queries

The formula

Here's the key formula. To find the sum from index ll to rr: sum(l,r)=pref[r]pref[l1]\text{sum}(l, r) = pref[r] - pref[l-1] Why does this work? pref[r]pref[r] contains a[1]+a[2]++a[r]a[1] + a[2] + \ldots + a[r]. Subtracting pref[l1]pref[l-1] removes a[1]++a[l1]a[1] + \ldots + a[l-1], leaving exactly a[l]++a[r]a[l] + \ldots + a[r]. One subtraction. O(1)O(1) per query.

With qq queries, total time is O(n+q)O(n + q) instead of O(nq)O(n \cdot q). For n=q=105n = q = 10^5, that's 2×1052 \times 10^5 operations instead of 101010^{10}.