Fenwick Trees
A Fenwick tree keeps running sums in one plain array so that both a prefix sum and a point update take O(log n). The range each slot covers comes from the lowest set bit of its index, so the whole structure is two short loops.
The Same Problem, Far Less Machinery
A Fenwick tree, also called a binary indexed tree (BIT), answers two requests on an array of numbers, both in O(log n): add a value at one index, and give the sum of the first i values.
A plain array does the update in O(1) but the sum in O(n). A prefix-sum array does the sum in O(1) but an update in O(n), because every later total changes. When both requests keep arriving in any order, this tree is the simplest structure that makes both fast.
The idea borrows from binary numbers. Every number is a sum of distinct powers of two, and the tree splits every prefix the same way: into blocks whose lengths are powers of two. Slot i stores the sum of the lowbit(i) values ending at index i, where lowbit(i) is the value of i's lowest set bit. Slot 8 (1000) covers 8 values, slot 12 (1100) covers 4, slot 7 (0111) covers 1.
Despite the name, there is no tree in memory: one array of n + 1 integers and two loops of about three lines each. The tree is the pattern of which slot's range sits inside which.
- Slot i covers indices i − lowbit(i) + 1 through i
- Odd slots cover one value; slot n covers everything when n is a power of two
- Slot 0 is left unused, so the array has n + 1 entries
The Lowbit Trick
Everything rests on the expression i & (-i), which keeps only the lowest set bit of i.
In two's complement, -i is ~i + 1. Flipping every bit turns the lowest 1 into a 0 and the zeros below it into ones; adding 1 then carries up through those ones and stops exactly at that bit. So i and -i share exactly one set bit, the lowest one, and & keeps just that. For i = 12 (1100), 12 & -12 = 4; for 7 (0111) it is 1; for 8 (1000) it is 8.
Removing the lowest bit, i -= i & -i, jumps to the slot that covers the block just before slot i's block. That is the query direction, and it runs down to 0.
Adding the lowest bit, i += i & -i, jumps to the next slot whose range contains index i. That is the update direction, and it runs up past n.
Each move clears a bit or carries it upward, so each loop runs at most about log₂ n + 1 times. That is the whole complexity argument.
- Python's unlimited-size integers still give the right answer for
i & -i - With unsigned types, use
i & (~i + 1)ori & (i ^ (i − 1)) - Index 0 breaks both loops: lowbit(0) = 0, so the index never moves
Query and Update
- prefix(i):
sum = 0; whilei > 0:sum += tree[i],i -= i & -i. - update(i, d): while
i ≤ n:tree[i] += d,i += i & -i. - sum(l, r):
prefix(r) − prefix(l − 1).
Prefix sum of the first i values: add tree[i], strip the lowest bit, repeat until i is 0. The blocks added are disjoint, their lengths are the powers of two in i's binary form, and together they cover 1..i exactly.
For i = 13 (1101), the walk reads slot 13 (1 value), slot 12 (4 values) and slot 8 (8 values): 1 + 4 + 8 = 13 values, exactly the prefix.
Point update, add d at index i: add d to tree[i], add the lowest bit to i, repeat while i ≤ n. This visits every slot whose range contains index i, and only those.
Range sum of l..r is prefix(r) − prefix(l − 1): two queries, still O(log n).
Building by calling update n times costs O(n log n). An O(n) build copies the array into tree, then for i = 1 to n adds tree[i] into tree[i + lowbit(i)] whenever that index is at most n.
| Fenwick tree | Segment tree | |
|---|---|---|
| Memory | n + 1 integers | 2n to 4n nodes |
| Code | Two short loops | Build, query and update, often recursive |
| Prefix or range sum | O(log n) | O(log n) |
| Range min / max | Not possible | O(log n) |
| Range update | Two trees, short code | Lazy propagation |
| Pick it when | The operation can be undone (sum, XOR) | Min, max, gcd or custom merges |
- Swapping the two directions gives a structure that returns wrong sums without crashing
set a[i] = xisupdate(i, x − a[i]), so keep a copy of the plain array- Use 64-bit totals when many updates can push a sum past 2³¹
Terms, operations, and practical uses
Binary indexing
- Lowest set bit
i & -ikeeps only the lowest 1 bit of i, and that value is the length of slot i's range. - Slot rangeSlot i holds the sum of indices
i − lowbit(i) + 1throughi. - 1-based indexinglowbit(0) is 0, so index 0 would never move; the tree starts at index 1.
Core operations
- Prefix sum queryAdd
tree[i], theni -= i & -i, until i is 0. - Point updateAdd the delta to
tree[i], theni += i & -i, until i passes n. - Constructionn updates in O(n log n), or O(n) by pushing each slot's total into
tree[i + lowbit(i)].
Comparisons
- Memoryn + 1 integers, against 2n to 4n nodes for a segment tree.
- Code sizeTwo loops of a few lines each, with no recursion.
- LimitsNo range minimum or maximum, because those cannot be undone by subtraction.
Code in Python, C++ and Java
class BIT:
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1)
def update(self, i, delta):
while i <= self.n:
self.tree[i] += delta
i += i & (-i)
def query(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & (-i)
return s
bit = BIT(8)
bit.update(3, 5)
print('prefix(7) =', bit.query(7))#include <iostream>
#include <vector>
using namespace std;
class BIT {
vector<int> tree;
public:
BIT(int n) : tree(n + 1, 0) {}
void update(int i, int delta) {
for (; i < (int)tree.size(); i += i & -i)
tree[i] += delta;
}
int query(int i) {
int sum = 0;
for (; i > 0; i -= i & -i)
sum += tree[i];
return sum;
}
};
int main() {
BIT bit(8);
bit.update(3, 5);
cout << "prefix(7) = " << bit.query(7) << '\n';
}public class Main {
static class BIT {
int[] tree;
BIT(int n) { tree = new int[n + 1]; }
void update(int i, int delta) {
for (; i < tree.length; i += i & -i)
tree[i] += delta;
}
int query(int i) {
int sum = 0;
for (; i > 0; i -= i & -i)
sum += tree[i];
return sum;
}
}
public static void main(String[] args) {
BIT bit = new BIT(8);
bit.update(3, 5);
System.out.println("prefix(7) = " + bit.query(7));
}
}Step through it
Running on BIT(8); update(3, 5); prefix(7)
Range Updates and Other Uses
The plain tree gives point update and range sum. Two standard variants extend it.
Range update, point read. Store a difference array in the tree. Adding v to every value in l..r becomes two point updates, +v at l and −v at r + 1, and the value at index i is prefix(i). Same two loops, different meaning. This is the usual fenwick tree range update.
Range update, range sum. Keep two trees B1 and B2. To add v on l..r, update B1 with +v at l and −v at r + 1, and B2 with +v·(l − 1) at l and −v·r at r + 1. Then the prefix sum is prefix(B1, i) · i − prefix(B2, i). It takes a few lines more than one tree and far fewer than lazy propagation.
Counting inversions. Go through the array from left to right. For each value x, the number of earlier values greater than x is (values inserted so far) − prefix(x); then insert x with update(x, 1). After coordinate compression this is O(n log n), and the same pattern answers Count of Smaller Numbers After Self.
Two dimensions. A tree of trees, with both loops nested, answers rectangle sums with point updates in O(log n · log m), using n · m memory instead of a 2D segment tree's much larger footprint.
- Values up to 10⁹ need coordinate compression before they can be indices
- Finding the smallest i with prefix(i) ≥ k takes O(log n) by walking down from the highest power of two
- Prefix minimums work only if values never increase; arbitrary ranges still need a segment tree
Choosing Between the Two Trees
The choice between a binary indexed tree and a segment tree comes down to one test: can the operation be undone? Range answers here come from prefix(r) − prefix(l − 1), so the operation needs an inverse. Sums and XOR have one. Minimum, maximum and gcd do not: knowing the minimum of 1..7 and of 1..2 tells you nothing about the minimum of 3..7.
If the operation is a sum or XOR, take the Fenwick tree: less code, less memory and a smaller constant factor, which is why it is the default in contests. If it is min, max, gcd, or needs many kinds of range update, use a segment tree.
If every update comes before every query, neither tree is needed. A difference array or prefix sums do the job in O(n + q).
- Both trees are O(log n) per operation; the choice is about what they can do
- Static array, no updates: prefix sums, O(1) per query
- Updates mixed with queries, sum only: Fenwick tree