Algolume

Fenwick tree (binary indexed tree)

Problem: You are given an array of n numbers. Support prefix sums and point updates, both in O(log n).

Input format: The first line contains n (1 ≤ n ≤ 100000). The second line contains n integers.

Output format: Print the sum of the whole array, computed through the tree.

Solution: The tree is stored in a single one-indexed array. Node i holds the sum of the range (i − lowbit(i), i], where lowbit(i) = i & -i is the lowest set bit. Walking up by i += lowbit(i) updates every node that covers a position; walking down by i -= lowbit(i) collects a prefix sum.

The visualisation reads the one-indexed tree array, so element 0 stays unused.

Visualise the algorithm! (Python3)

For the visualisation to work reliably, keep n ≤ 40.

Logical name Variable name
Fenwick tree array