Short answer: A Fenwick tree, or binary indexed tree, stores partial sums so that the prefix sum through index i, and a point update at i, both run in O(log n). The index trick is the least significant set bit: i & −i in two’s complement. That bit names the range of values the node covers. The structure uses n cells, needs no pointers, and does not by itself represent an arbitrary range update plus an arbitrary range query without a second tree or a difference encoding.
What the problem actually asks
A raw array answers a point update in constant time and a prefix sum in linear time. A prefix-sum array answers the sum in constant time and a point update in linear time, because every later prefix changes. A Fenwick tree keeps both operations logarithmic by storing, at index i, the sum of a segment ending at i whose length is the least significant set bit of i.
Walking i down by clearing that bit visits O(log n) segments that partition the prefix. Walking i up by adding that bit visits every segment that contains i, which is the update path.
What the algorithm guarantees
Point add and prefix sum are O(log n). A range sum from l to r is prefix(r) − prefix(l−1). Extra memory is n numbers, usually 1-based so that the bit trick never sees index 0. The tree does not store a search-tree order of arbitrary keys. The indices are 1..n. Coordinate compression is the usual way to feed it sparse or non-integer positions.
Range add together with point query is the difference-array encoding: add v at l and −v at r+1, and a prefix sum is the point value. Range add together with range query needs two Fenwick trees, storing the coefficients of a linear function of the index. A segment tree represents those range operations more directly and uses about twice the memory.
The working steps
- Allocate a 1-based array T of length n, initially zero.
- To add v at index i, while i ≤ n, add v to T[i] and then add i & −i to i.
- To read the prefix sum through i, set s = 0, and while i > 0, add T[i] to s and subtract i & −i from i.
- A range sum on [l, r] is prefix(r) − prefix(l−1), with prefix(0) = 0.
- Build from an existing array by calling add at each index, which is O(n log n), or by a linear accumulation that fills each cell from its children in index order.
The bit trick is for prefix-shaped segments on a 1-based line. It is not a segment tree, and it is not a sum over an arbitrary subset that is not a prefix or a difference of prefixes. Two-dimensional Fenwick trees exist and multiply the logarithm. A sparse dynamic version needs a hash map or an implicit tree and loses the plain array.
Approaches that look simpler and fail
| Approach | Why it fails when the index is zero-based and the bit step is left unchanged |
|---|---|
| Start updates at index 0 | The least significant bit of 0 is 0, so i += i & −i never moves. The array is 1-based, or the keys are shifted by one. |
| Store the whole prefix in every cell and still jump by the low bit | The cell at i covers only the segment of length i & −i ending at i. A full prefix in every cell is a prefix array, and the jump double-counts. |
| Update only T[i] and not the ancestors | Later prefixes that include i read those ancestors. Skipping the upward walk leaves them stale. |
| Expect a range assign of an interval in one visit | A Fenwick tree of values supports point updates. A range assignment is a segment tree with lazy tags, or a difference encoding if the query shape allows it. |
Arbitrary range updates with lazy propagation belong to a segment tree. A static prefix array is enough when the values never change. The Fenwick tree is the compact structure for point updates and prefix sums.
A working example
The Bash script and the Python script are 1-based Fenwick trees. An update adds the step i & -i. A prefix sum subtracts it. Both print the prefix through index 3 and the total, 6 15.
n=5
for ((i=0; i<=n; i++)); do t[i]=0; done
add() {
local i=$1 d=$2
while (( i <= n )); do
t[i]=$((t[i]+d))
i=$(( i + (i & -i) ))
done
}
prefix() {
local i=$1 s=0
while (( i > 0 )); do
s=$((s + t[i]))
i=$(( i - (i & -i) ))
done
echo "$s"
}
vals=(1 2 3 4 5)
for ((i=1; i<=n; i++)); do add "$i" "${vals[i-1]}"; done
echo "$(prefix 3) $(prefix 5)"
class Fenwick:
def __init__(self, n):
self.t = [0] * (n + 1)
def add(self, i, delta):
while i < len(self.t):
self.t[i] += delta
i += i & -i
def prefix(self, i):
s = 0
while i > 0:
s += self.t[i]
i -= i & -i
return s
tree = Fenwick(5)
for i, v in enumerate([1, 2, 3, 4, 5], 1):
tree.add(i, v)
assert tree.prefix(3) == 6 and tree.prefix(5) == 15
print(tree.prefix(3), tree.prefix(5))
Where it is used
A Fenwick tree is the compact array for an online histogram: update one bucket, read a prefix total. Inversion counting and live scoreboards use that shape. A segment tree stores more nodes and answers a wider family of range updates.
When you can drop this algorithm
Drop a Fenwick tree when the queries are static. A prefix array answers them in constant time. Drop it when the updates are arbitrary range assignments. Use a segment tree. Keep it for point add and prefix or range sum on a line of indices.
Why this stays published
We publish this so a search for a Fenwick tree returns the least-significant-bit walk and the 1-based index it requires. A Fenwick tree answers a prefix sum and a point update in O(log n) time by walking indices in steps of their least significant set bit.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
