A Fenwick tree, or binary indexed tree (BIT), maintains prefix sums of an array that keeps changing. Both "add to one element" and "sum of the first i elements" run in O(log n), using a single array of n + 1 numbers and a loop of about five lines each. Its secret is one bit trick, i & -i, which tells every index how large a block of the array it is responsible for.
Think of it like
Receipt jars sized by powers of two
A shop keeps its daily receipts in jars: one jar for days 1 to 8, one for days 9 to 12, one for day 13 alone, and so on, every jar covering a power-of-two run of days. To total days 1 through 13, you add just three jars (8 + 4 + 1 days, the binary digits of 13). When a late receipt for day 5 turns up, you drop a note into the few jars that cover day 5. Few jars to read, few jars to update.
The idea: prefixes split along binary digits
Every number is a sum of distinct powers of two, so every prefix [1, i] can be cut into blocks whose lengths are those powers. With 13 = 1101₂, the prefix [1, 13] is [1, 8] + [9, 12] + [13, 13]. A Fenwick tree stores exactly these blocks: entry tree[i] (1-based) holds the sum of the lowbit(i) elements ending at i, where lowbit(i) is the value of the lowest set bit of i.
| i | Binary | lowbit(i) | tree[i] covers | Value for a = [2, 1, 5, 3, 4, 6, 0, 7] |
|---|---|---|---|---|
| 1 | 0001 | 1 | a[1] | 2 |
| 2 | 0010 | 2 | a[1..2] | 3 |
| 3 | 0011 | 1 | a[3] | 5 |
| 4 | 0100 | 4 | a[1..4] | 11 |
| 5 | 0101 | 1 | a[5] | 4 |
| 6 | 0110 | 2 | a[5..6] | 10 |
| 7 | 0111 | 1 | a[7] | 0 |
| 8 | 1000 | 8 | a[1..8] | 28 |
lowbit: i & −i
In two's complement, −i = ~i + 1. Inverting i turns its lowest set bit into a 0 and all the zeros below it into 1s; adding 1 ripples those 1s back to 0 and restores that one bit. Every bit above it stays inverted. So i & −i keeps only the lowest set bit.
i = 12 = 0000 1100
~i = 1111 0011
-i = ~i+1 = 1111 0100
i & -i = 0000 0100 = 4Prefix query: strip the lowest bit
To sum a[1..i], add tree[i], then jump to the end of the previous block with i -= lowbit(i), and repeat until i is 0. Each step clears one set bit, so there are at most ⌊log₂ n⌋ + 1 steps.
- 1
i = 7 (0111)
Add
tree[7]= a[7] = 0. Clear the lowest bit: i = 6. - 2
i = 6 (0110)
Add
tree[6]= a[5..6] = 10. Clear the lowest bit: i = 4. - 3
i = 4 (0100)
Add
tree[4]= a[1..4] = 11. Clear the lowest bit: i = 0, stop. - 4
Result
prefix(7) = 0 + 10 + 11 = 21, which matches 2 + 1 + 5 + 3 + 4 + 6 + 0.
Point update: add the lowest bit
To add delta to a[i], every entry whose block contains position i must change. Starting at i, the next such entry is always i + lowbit(i), so loop tree[i] += delta; i += lowbit(i) while i <= n. Updating position 3 touches tree[3], tree[4] and tree[8]; position 5 touches 5, 6, 8 and 16 in a tree of size 16.
Range sums from two prefixes
Building in O(n)
Calling add once per element costs O(n log n). Instead, copy the array into tree, then for i from 1 to n push each finished entry into its parent: j = i + lowbit(i); if j <= n, tree[j] += tree[i]. Every entry is complete by the time it is pushed, because all of its contributors have smaller indices. (Equivalently, tree[i] = P[i] − P[i − lowbit(i)] from a prefix-sum array P.)
Variant: range update, point query
Flip the roles with a difference array d, where a[i] = d[1] + … + d[i]. Adding v to every element of [l, r] changes only two differences: d[l] += v and d[r + 1] −= v. Store d in a Fenwick tree and a single value a[i] is just prefix(i).
class RangeAddBIT:
"""Add v to a[l..r] and read a single a[i], both O(log n). 0-based API."""
def __init__(self, n: int):
self.n = n
self.tree = [0] * (n + 2)
def _add(self, i: int, v: int) -> None: # i is 1-based
while i <= self.n:
self.tree[i] += v
i += i & -i
def range_add(self, l: int, r: int, v: int) -> None:
self._add(l + 1, v) # difference array: +v at l
self._add(r + 2, -v) # and -v just after r
def point_query(self, idx: int) -> int:
i, s = idx + 1, 0 # a[idx] = prefix sum of differences
while i > 0:
s += self.tree[i]
i -= i & -i
return sRange update and range query is also possible with two Fenwick trees, one over d[j] and one over j · d[j], using the identity below.
Two dimensions
A 2D Fenwick tree nests the loops: for x in BIT walk over rows: for y in BIT walk over columns. Point updates and prefix-rectangle sums cost O(log n · log m), and any rectangle sum follows by inclusion-exclusion from four prefix rectangles. It is the go-to structure for a mutable 2D grid of sums.
Application: counting inversions
An inversion is a pair i < j with a[i] > a[j]. Scan the array from right to left and keep a Fenwick tree of the values seen so far (counts indexed by value). For each element, the number of already-seen values smaller than it is exactly the number of inversions it starts. Then mark it as seen. If values are large or negative, first replace them by their rank (coordinate compression).
| Element (right to left) | Rank | Seen and smaller | Running total |
|---|---|---|---|
| 1 | 1 | none: 0 | 0 |
| 6 | 4 | {1}: 1 | 1 |
| 2 | 2 | {1}: 1 | 2 |
| 5 | 3 | {1, 2}: 2 | 4 |
[5, 2, 6, 1] has 4 inversions: (5,2), (5,1), (2,1) and (6,1). Total cost O(n log n), the same as the merge-sort method in Merge Sort.Fenwick tree vs segment tree
Fenwick tree
- n + 1 integers of memory
- Two tiny loops; very fast in practice
- Prefix sums, XOR, counts; range ops via differences
- Binary-lifting search finds the first prefix >= k in O(log n)
Segment tree
- 2n to 4n memory and more code
- Any associative operation: min, max, GCD, custom merges
- Lazy propagation for general range updates
- Easier to extend with extra per-node data
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
Point update add(i, delta) | O(log n) | O(1) | Climb with i += i & −i |
Prefix query prefix(i) | O(log n) | O(1) | Descend with i −= i & −i |
| Range sum | O(log n) | O(1) | prefix(r) − prefix(l − 1) |
| Build | O(n) | O(n) | Push each entry into its parent once |
| Range add + point query | O(log n) | O(n) | Fenwick tree over a difference array |
| 2D update / rectangle query | O(log n · log m) | O(n · m) | Nested loops |
| Count inversions | O(n log n) | O(n) | After coordinate compression |
The tree uses exactly n + 1 slots; index 0 is unused so that the lowbit loops terminate.
Implementation
1-based internally so the lowbit loops work; the public methods take 0-based indices.
class FenwickTree:
def __init__(self, a: list[int]):
self.n = len(a)
self.tree = [0] + list(a) # tree[i] covers (i - lowbit(i), i]
for i in range(1, self.n + 1): # O(n) build: push into the parent
j = i + (i & -i)
if j <= self.n:
self.tree[j] += self.tree[i]
def add(self, idx: int, delta: int) -> None:
"""a[idx] += delta."""
i = idx + 1
while i <= self.n:
self.tree[i] += delta
i += i & -i # next entry whose block covers i
def prefix(self, idx: int) -> int:
"""Sum of a[0..idx], inclusive; prefix(-1) is 0."""
i, s = idx + 1, 0
while i > 0:
s += self.tree[i]
i -= i & -i # drop the lowest set bit
return s
def range_sum(self, l: int, r: int) -> int:
return self.prefix(r) - self.prefix(l - 1)
ft = FenwickTree([2, 1, 5, 3, 4, 6, 0, 7])
print(ft.range_sum(2, 6)) # 18
ft.add(3, 6) # a[3]: 3 -> 9
print(ft.range_sum(2, 6)) # 24Key takeaways
tree[i]stores the sum of the lowbit(i) elements ending at i, where lowbit(i) =i & -iis the lowest set bit.- Prefix queries strip the lowest bit (
i -= i & -i); point updates add it (i += i & -i). Both take O(log n). - Range sums come from two prefix queries, so the operation must be invertible: sums and XOR work, min and max do not.
- Build in O(n) by pushing each entry into
i + lowbit(i); a difference array turns it into range-update, point-query. - Classic uses: mutable prefix sums, counting inversions and smaller-element counts, order statistics in a stream.
Common pitfalls
- Using index 0 inside the loops:
0 & -0is 0, so the update loop never advances and runs forever. Keep the tree 1-based. - Off-by-one errors when mixing 0-based input with the 1-based tree, especially
prefix(l − 1)for range sums. - Trying to answer range minimum or maximum with prefix differences.
- Forgetting coordinate compression when values are large or negative, which makes the tree enormous or indexes out of bounds.
- Overflowing 32-bit sums; use 64-bit accumulators.
Interview tips
- Explain lowbit with a concrete binary example such as 12 = 1100₂ giving 4; it makes the rest obvious.
- Say "query removes the lowest bit, update adds it" and write both loops from memory.
- For "count smaller to the right" or inversion problems, describe the right-to-left scan with compression before coding.
- If the interviewer asks for range minimum or lazy range assignment, switch to a segment tree and explain why.
Real-world applications
- Mutable prefix sums in leaderboards, histograms and cumulative frequency tables.
- Counting inversions and "smaller elements to the right" in O(n log n).
- Order statistics in a stream: rank of a value or the k-th smallest via binary lifting.
- Arithmetic coding, which maintains cumulative symbol frequencies (Fenwick's original 1994 motivation).
- 2D grids of counts, such as dynamic heatmaps or mutable rectangle-sum queries.
Practice problems
Test yourself
What is 12 & -12?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.