class Fenwick { tree: number[]; constructor(size: number) { this.tree = new Array(size + 1).fill(0); } add(index: number, delta: number) { for (let i = index + 1; i < this.tree.length; i += i & -i) {this.tree[i] += delta;
}
}
prefix(count: number) {let sum = 0;
for (let i = count; i > 0; i -= i & -i) {sum += this.tree[i];
}
return sum;
}
rangeSum(from: number, to: number) { return this.prefix(to + 1) - this.prefix(from); } static build(values: number[]) {const fenwick = new Fenwick(values.length); values.forEach((value, index) => fenwick.add(index, value));
return fenwick;
}
}
A Fenwick tree over 8 values. Node i stores the sum of the range (i − lowbit(i), i], where lowbit is the lowest set bit of i.
Understanding Fenwick tree
The idea
A Fenwick tree, or binary indexed tree, is a plain array of n + 1 numbers where slot i holds the sum of a range that ends at i and whose length is the lowest set bit of i: slot 6 (110₂) covers two values, slot 8 (1000₂) covers eight. Those ranges nest into a tree, and the tree is never stored: the parent of i on a prefix query is i minus its lowest bit, and on an update i plus it.
A prefix sum walks down from i clearing the lowest bit each time, so it adds at most log n slots. A point update walks up adding the lowest bit, touching the log n slots whose range covers the index. Twenty lines and no pointers, which is why it is the usual answer when the operation can be undone, as sums can.
The four stages
Complexity
Versus its siblings
Pseudocode
ADD(index, delta): i ← index + 1; while i ≤ n: tree[i] += delta; i ← i + lowbit(i)
PREFIX(count): sum ← 0; i ← count; while i > 0: sum += tree[i]; i ← i − lowbit(i); return sum
RANGE(a, b) = PREFIX(b + 1) − PREFIX(a)
lowbit(i) = i & −i, the value of the lowest set bit
When to use
Pitfalls
History
Boris Ryabko proposed the structure in 1989 and Peter Fenwick described it independently in 1994 for cumulative frequency tables in arithmetic coding, where every symbol updates a count and every decode needs a prefix sum. It is now a fixture of competitive programming under the name binary indexed tree.