Fenwick tree

Fenwick tree (aka Binary indexed tree) is a data structure that maintains a sequence of elements, and is able to compute cumulative sum of any range of consecutive elements in $$O(\log n)$$ time. Changing value of any single element needs $$O(\log n)$$ time as well.

The structure is space-efficient in the sense that it needs the same amount of storage as just a simple array of $$n$$ elements.

The basic rule that the structure works on is that, just like a number can be represented as a sum of some powers of two, so can a cumulative sum be represented as a sum of some partial cumulative sums.

Every index in the cumulative sum array, say i, is responsible for the cumulative sum from the index i to (i - (1<<r) + 1), where r represents the last 1 bit set int the index i.