Lesson contents

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.

Start2 5 3 4
Result10
Main.java
public class Main {
    public static void main(String[] args) {
        int[] blocks = {0, 2, 7, 3, 14};
        int i = 3;
        int total = 0;
        while (i > 0) {
            total += blocks[i];
            i -= i & -i;
        }
        System.out.println(total);
    }
}
Output
10
Advertisements

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?

Start14 +1
Result15

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?

Start1 4 / 2
Result7

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?

Start23−9
Result14

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.