01The problem: changes and range sums
You are given a sequence of n numbers, and two kinds of requests keep arriving (slide 2):
- change the value of element i;
- report the sum of the elements on an interval [x, y].
If the array never changes, prefix sums solve it: store prefix[i] = a[1] + … + a[i], and the sum on [x, y] is prefix[y] − prefix[x − 1]. In the lecture’s array of 16 numbers the sum on [6, 13] is 3+1+4+2+5+2+2+3 = 22, or, with a single subtraction, 33 − 11 = 22.
With dynamic data this breaks down: after every change of a[i], all prefix sums from i to n must be recounted, O(n) work per change. The Fenwick tree (binary indexed tree, BIT) handles both requests in O(log n) in the worst case, and its code is very short.