Fenwick trees
A Fenwick tree stores sums for overlapping queries using reusable blocks. A prefix query combines disjoint blocks. An update changes the blocks that contain the edited position.
Simple example
For the first three items, take the block for position 3, worth 3, and the block ending at 2, worth 7. Print 10.
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int blocks[] = {0, 2, 7, 3, 14};
int i = 3;
int total = 0;
while (i > 0) {
total += blocks[i];
i -= i & -i;
}
printf("%d\n", total);
}
10
Everyday examples
Correct a ticket count
Four desks sell 2, 5, 3 and 4 tickets. Desk two reports one extra sale. What is the new total?
Add one to the block ending at 2 and the larger block ending at 4. The total rises to 15.
Read three days of sales
Daily sales are 1, 4, 2 and 8. How do you sum the first three?
Use the block for days one and two, worth 5, and the block for day three, worth 2.
Find deliveries within a range
The first five deliveries total 23 crates. The first two total 9. What arrived in deliveries three through five?
Ask the tree for both prefix totals and subtract to isolate the middle range.
Cost and limits
A one-based Fenwick tree supports point updates and prefix sums in O(log n). Index zero is the stopping boundary.