11. Fenwick Tree (Binary Indexed Tree)
An array where entry i stores the sum of a block of positions ending at i, sized by i’s lowest set bit. Prefix sums and point updates both take O(log n) with a few lines of code.
How it works
A Fenwick tree answers ‘sum of the first i items’ while items keep changing. Plain prefix sums answer queries in O(1) but cost O(n) per update; a Fenwick tree makes both O(log n).
Positions are 1-indexed. lowbit(i) = i & -i is the value of i’s lowest set bit, and tree[i] holds the sum of positions i - lowbit(i) + 1 through i.
- prefix_sum(i): add
tree[i], then strip the lowest bit (i -= lowbit(i)) until i is 0. - add(i, delta): add delta to
tree[i], then move to the next block that also covers position i (i += lowbit(i)).
The diagram shows each node’s block and the update path upward.
Diagram
graph BT
f1["tree 1: positions 1 to 1, sum 3"]
f2["tree 2: positions 1 to 2, sum 5"]
f3["tree 3: positions 3 to 3, sum -1"]
f4["tree 4: positions 1 to 4, sum 10"]
f5["tree 5: positions 5 to 5, sum 5"]
f6["tree 6: positions 5 to 6, sum 9"]
f7["tree 7: positions 7 to 7, sum -3"]
f8["tree 8: positions 1 to 8, sum 19"]
f1 --> f2
f2 --> f4
f3 --> f4
f4 --> f8
f5 --> f6
f6 --> f8
f7 --> f8
Step-by-step trace
Input: Values [3, 2, -1, 6, 5, 4, -3, 3] at positions 1 to 8, so tree = [3, 5, -1, 10, 5, 9, -3, 19]. Query prefix_sum(7).
| i | i in binary | covers positions | tree[i] | running total | next i = i - lowbit(i) |
|---|---|---|---|---|---|
| 7 | 111 | 7..7 | -3 | -3 | 6 |
| 6 | 110 | 5..6 | 9 | 6 | 4 |
| 4 | 100 | 1..4 | 10 | 16 | 0 |
Result: prefix_sum(7) = 16, which equals 3 + 2 + -1 + 6 + 5 + 4 + -3, using only 3 lookups.
Input: Then add(3, +2): position 3 changes from -1 to 1.
| i | i in binary | covers positions | tree[i] after | next i = i + lowbit(i) |
|---|---|---|---|---|
| 3 | 11 | 3..3 | 1 | 4 |
| 4 | 100 | 1..4 | 12 | 8 |
| 8 | 1000 | 1..8 | 21 | 16 (past n, stop) |
Result: Only 3 entries changed. tree is now [3, 5, 1, 12, 5, 9, -3, 21].
Complexity
| Operation | Time | Space |
|---|---|---|
| prefix_sum / range_sum | O(log n) | O(1) |
| add (point update) | O(log n) | O(1) |
| Build by n adds | O(n log n) | O(n) |
Python reference implementation
class FenwickTree:
"""Binary indexed tree over positions 1..n: point add, prefix sum."""
def __init__(self, n):
self.tree = [0] * (n + 1)
@classmethod
def from_list(cls, values):
ft = cls(len(values))
for i, v in enumerate(values, 1):
ft.add(i, v)
return ft
def add(self, i, delta):
while i < len(self.tree):
self.tree[i] += delta
i += i & -i # jump to the next node that covers i
def prefix_sum(self, i):
total = 0
while i > 0:
total += self.tree[i]
i -= i & -i # drop the lowest set bit
return total
def range_sum(self, left, right):
return self.prefix_sum(right) - self.prefix_sum(left - 1)
Common mistakes and tips
- Fenwick trees are 1-indexed; shifting by one is the classic bug.
range_sum(l, r) = prefix_sum(r) - prefix_sum(l - 1).- Count inversions or ‘smaller numbers after self’ by adding 1 at each value’s rank while scanning.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Tries (Prefix Trees) | Next: Segment Tree (Range Sum Queries) |