## Fenwick Trees

### July 20, 2018

There are some algorithms in coding theory where cumulative frequency tables must be maintained. This requires two tasks to be performed on an array of integers:

1) Calculate the cumulative sum of the first *n* elements of the array.

2) Modify the value of an element of the array.

One approach is to maintain an array of the elements, so that an element can be modified in O(1) time but calculating the cumulative sum requires O(*n*)time. Another approach is maintain an array of the cumulative sumes, so that a cumulative sum can be calculated in O(1) time but modifying a single element of the array takes O(*n*) time.

A Fenwick tree performs both operations in O(log *n*) time. The tree is normally embedded in a 1-based array, with the children of node *i* at nodes 2*i* and 2*i* + 1. Each element with index *i* a power of 2 contains the sum of the first *i* elements. Each element with index *i* a sum of two powers of 2 contains the sum of the elements since the preceding power of 2. In general, each element contains the sum of the values since its parent in the tree, found by clearing the least-significant bit in the index. Wikipedia has a good description of Fenwick trees.

For example, to find the sum of the first 11_{10} = 1011_{2} items in the array, note that 11 has three bits set, so add elements 1000_{2}, 1010_{2}, and 1011_{2}. To modify the 11th element, modify 1011_{2}, 1100_{2}, 10000_{2}, and all higher powers of 2 up to the size of the array.

Your task is to implement Fenwick trees. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Here’s a solution in Python.