Don't memorize the Fenwick tree — watch the bits do the walking. A binary indexed tree stores clever partial sums so a prefix-sum query and a single-element update both finish in O(log n). The whole thing runs on one arithmetic trick: i & -i, the lowest set bit, tells each cell exactly which range it owns and how far to hop next.
binary indexed tree · i & -i · query down · update up
LOWBIT
i & -i — the lowest set bit of i; the size of the block cell i owns.
TREE CELL
tree[i] holds the sum of a block of length lowbit(i) ending at i.
QUERY
Prefix sum: add tree[i], then i −= i & -i, until 0.
UPDATE
Bump a point: add delta, then i += i & -i, until past n.
Top is the array A (1-indexed); below is the tree[], where each cell owns a block whose length is its lowest set bit. Press Step to see a prefix query walk down, then a point update walk up.
lowbit(i) = i & -i
Overview
Phase
—
Running sum
One array, both operations fast
A prefix-sum array answers range sums in O(1) but an update costs O(n). A Fenwick tree keeps updates fast too — O(log n) — by storing overlapping partial sums instead of full prefixes. The magic index scheme is what makes it tiny: cell i covers the block of length lowbit(i) ending at i. Cell 6 (binary 110, lowbit 2) covers positions 5–6; cell 4 (100, lowbit 4) covers 1–4; cell 8 (1000) covers everything. To sum a prefix, you hop across a handful of these blocks that tile it exactly.
01
Each cell owns a block
tree[i] = sum of A over [i − lowbit(i) + 1 .. i]. Different cells cover different power-of-two ranges.
02
Query walks down
Prefix sum of 1..i: add tree[i], then i −= i & -i, repeat to 0. About log n cells, all disjoint.
03
Update walks up
Change A[i] by delta: add delta to tree[i], then i += i & -i, repeat past n. Only the cells that include i change.
04
Range sum
Sum of [l..r] = prefix(r) − prefix(l − 1). Two queries, still O(log n).
Prefix query
O(log n)
Point update
O(log n)
Build
O(n)
Space
O(n)
The Fenwick tree is a favorite because it is so small — a single array and two three-line loops — and cache-friendly. It handles prefix and range sums with point updates beautifully. When you need min, max, gcd, or range updates, reach for a segment tree instead; when the data never changes, a plain prefix-sum array is simpler still.
Check yourself
1 · What does i & -i compute?
The lowbit is both the range length for cell i and the hop size for moving between cells.
2 · How does a prefix-sum query move through the tree?
Start at i, add tree[i], then i −= i & -i until 0 — the disjoint blocks tile 1..i.
3 · When is a Fenwick tree preferred over a segment tree?
Fenwick shines for sums with point updates; segment trees handle min/max/gcd and range updates.
The picture: blocks that tile a prefix
The page’s array in cells 1 to 8, with each tree cell drawn as a bar over the cells it owns. A prefix query picks the bars that tile 1..i from the right. For prefix(7) those are the highlighted three: cell 7 alone, cells 5–6, and cells 1–4.
Worked example, step by step
Use the page’s array [3, 2, −1, 6, 5, 4, −3, 3], 1-indexed. The tree is [3, 5, −1, 10, 5, 9, −3, 19] for cells 1 to 8. Ask for prefix(7), then add 5 to cell 3 and ask again. The binary column shows why the walk is short: each query step clears the lowest 1 bit of i, and each update step adds it back.
Operation
i
Binary
i & −i
tree[i]
Running sum
prefix(7)
7
0111
1
−3
−3
prefix(7)
6
0110
2
9
6
prefix(7)
4
0100
4
10
16
update(3, +5)
3
0011
1
−1 → 4
—
update(3, +5)
4
0100
4
10 → 15
—
update(3, +5)
8
1000
8
19 → 24
—
prefix(7) again
7, 6, 4
—
—
−3, 9, 15
21
The query visits 7, 6, 4 because 111 → 110 → 100 → 000 drops one set bit at a time, so the number of cells touched is the number of 1 bits in i: three for 7. The sum 16 equals 3 + 2 − 1 + 6 + 5 + 4 − 3 computed the slow way. The update goes the other direction, 3 → 4 → 8 → stop (16 is past the end), and touches exactly the cells whose blocks contain cell 3. Tree cells 7 and 6 do not contain cell 3, so the second query reads the same three cells and sees only the cell-4 change: 16 becomes 21, up by 5. Both operations touched 3 cells on an 8-cell tree, which is where log₂ 8 = 3 comes from.
Complexity and trade-offs
Case
Time
Space
Why
Fenwick tree
O(log n) query and update
O(n)
For n = 1,000,000 a query touches at most 19 cells and an update at most 20.
Plain array
O(1) update, O(n) query
O(n)
Fast to change, slow to sum: a prefix near the end reads nearly every cell.
Prefix-sum array
O(1) query, O(n) update
O(n)
Changing the first element rewrites all 1,000,000 prefixes at n = 1,000,000.
Segment tree
O(log n) query and update
O(2n) to O(4n)
Roughly double the memory and more code, but it supports any associative operation, and range updates with lazy propagation.
Fenwick build, linear form
O(n)
O(n)
Pushing each cell into its parent costs n steps; calling update for every element costs 10,095,616 at n = 1,000,000.
The Fenwick tree is the compact choice when the operation has an inverse. Sum, count and xor have one (subtract, subtract, xor again), so a range is a difference of two prefixes. Min and max do not, and that is the point where a segment tree is required. The other price is readability: the structure is an array whose meaning lives in bit arithmetic, so it is easy to use correctly and hard to debug when wrong.
Common mistakes
Using index 0
The loops need 1-based indices because 0 & −0 is 0. An update at index 0 never moves: i += i & −i adds 0 and the loop was still running after 1000 iterations when it was cut off. Convert inputs with i + 1 at the boundary.
Writing a value instead of a delta
update(i, d) adds. To set cell 3 of [3, 2, −1, 6, 5, 4, −3, 3] to 5, pass 5 − A[3] = 6. Passing 5 makes the total 24 instead of 25. Keep a copy of the array to compute the difference.
Off by one in the range sum
A range is prefix(r) − prefix(l − 1). With prefix(l) the left cell is lost: sum of cells 3 to 5 should be 10 (−1 + 6 + 5), but prefix(5) − prefix(3) gives 11.
Building the tree by copying the array
Setting tree = [0, ...A] does not build the block sums. Then prefix(4) returns 6, the value of cell 4 alone, instead of 10. Build with n calls to update, or with the linear parent-push loop.
Using it for max or min with decreasing values
A max-Fenwick keeps the largest value seen, so it cannot undo one. Lowering cell 4 from 6 to 1 leaves prefixMax(4) at 6, though the true maximum of the first four cells is now 3. For this use a segment tree, or only ever increase values.
Where this shows up
Counting inversions
Process the array from the right; for each value, count how many smaller values are already in the tree, then insert it. Values are first replaced by ranks. The page’s array [3, 2, −1, 6, 5, 4, −3, 3] has 15 inversions, matching a quadratic check.
Rank and leaderboard queries
Keep a count per score bucket; “how many players scored below x” is a prefix query, and a new score is a +1 update. Both stay logarithmic as the player count grows.
k-th smallest by binary descent
Store counts per value and walk down the tree by powers of two instead of calling prefix repeatedly. On the same eight numbers it finds the 5th smallest, 3, in one pass of 4 steps.
Two dimensions and range updates
A tree of trees gives sums over a rectangle of a matrix. Storing differences instead of values gives range-add with point query, and two trees together give range-add with range-sum.
SOLVE IT YOURSELF
Solve it: prefix sums that survive updates
A prefix-sum array answers range queries in O(1) but costs O(n) per update. A Fenwick tree makes both O(log n) — using nothing but an array and the lowest set bit. Python or TypeScript, running for real in your browser.
YOUR TASK
Implement update(i, delta) and prefix_sum(i) on a Fenwick tree (BIT). Indices in the public API are 0-based, inclusive; internally the tree is 1-based. range_sum is provided and builds on your two methods.
HINTS — 6 IDEAS
The tree is 1-based internally, because the bit trick needs a non-zero index. Convert with i += 1 on the way in.
i & -i isolates the lowest set bit — the size of the range that node is responsible for.
update walks up, adding that lowest bit: i += i & -i, while i <= n. Every node covering the position gets the delta.
prefix_sum walks down, stripping it: i -= i & -i, while i > 0, accumulating as it goes.
Both loops run at most log₂(n) times, because each step clears or adds one bit.
Getting the two directions backwards is the classic bug — it produces plausible-looking but wrong sums rather than an error.
CPython · WebAssembly✓ Solved
1
1
Questions
Why is it 1-indexed?
The lowbit walk relies on index 0 being the terminator for queries (you stop when i reaches 0) and the powers-of-two block structure lining up from 1. A 0-indexed array is shifted by one internally.
Can a Fenwick tree do range updates?
Yes, with a second BIT (or a difference-array trick), you can support range updates and range queries, still in O(log n). It is a common competitive-programming extension.
How do you build it in O(n)?
Instead of n separate updates (O(n log n)), copy the values in and push each cell contribution to its immediate parent (i + lowbit(i)) once, which fills the whole tree in linear time.
Prefix sums that update — in log time.
One array, one bit trick. Query walks down, update walks up, both O(log n).