Sub topic 11
Fenwick tree: what each cell stores
This chapter assumes you know binary numbers, bitwise AND, two's complement negation, and the idea of a prefix sum. It also assumes you know that i & -i isolates the lowest set bit, which is the lowbit trick from the previous chapter.
The idea
A prefix-sum array stores the sum of everything up to position i. A Fenwick tree (also called a binary indexed tree) stores less in each cell: only a short block that ends at i. Short blocks are cheap to update, and a few blocks can be combined to rebuild any prefix.
The tree is 1-indexed. Cell t[i] holds the sum of the lowbit(i) elements that end at position i:
t[i] = a[i - lowbit(i) + 1] + ... + a[i]So the block size is the value of the lowest set bit of i. Odd indices have lowbit 1, so they store only themselves. Powers of two have a lowbit equal to the index, so they store the whole prefix.
Cells for n = 8
| i | Binary | lowbit(i) | Range covered |
|---|---|---|---|
| 1 | 0001 | 1 | a[1..1] |
| 2 | 0010 | 2 | a[1..2] |
| 3 | 0011 | 1 | a[3..3] |
| 4 | 0100 | 4 | a[1..4] |
| 5 | 0101 | 1 | a[5..5] |
| 6 | 0110 | 2 | a[5..6] |
| 7 | 0111 | 1 | a[7..7] |
| 8 | 1000 | 8 | a[1..8] |
The ranges nest like a forest. Each block is contained in a larger block that starts at the same place or ends further right.
Each arrow goes from i to i + lowbit(i). That is the next cell whose block includes i. An update to position 3 must change cells 3, 4, and 8, and the next chapter uses this path.
Checking it in code
This script builds each cell directly from its definition, which is slow but shows the layout:
def lowbit(i):
return i & -i
a = [5, 2, 7, 1, 3, 4, 6, 8] # a[1..8] stored at indices 0..7
n = len(a)
t = [0] * (n + 1) # index 0 is unused
for i in range(1, n + 1):
lo = i - lowbit(i) + 1
t[i] = sum(a[lo - 1:i]) # slice shifts to zero-based
print(f"t[{i}] covers a[{lo}..{i}] = {t[i]}")The output is:
t[1] covers a[1..1] = 5
t[2] covers a[1..2] = 7
t[3] covers a[3..3] = 7
t[4] covers a[1..4] = 15
t[5] covers a[5..5] = 3
t[6] covers a[5..6] = 7
t[7] covers a[7..7] = 6
t[8] covers a[1..8] = 36Why this layout works
To get prefix(7), you need a[1..7]. The blocks t[7], t[6], and t[4] cover a[7..7], a[5..6], and a[1..4]. These do not overlap, and together they are exactly a[1..7]. Each step drops the lowest set bit: 7 (111) goes to 6 (110), then to 4 (100), then to 0.
An index has at most about log2(n) set bits. So any prefix needs at most that many blocks, and any update touches at most that many cells.
Exercise
For n = 16, which positions of a does cell t[12] cover, and which cells does a prefix query for position 12 read?
Show answer
12 is 1100 in binary, so lowbit(12) = 4 and t[12] covers a[9..12]. The prefix query for 12 reads t[12], then drops the lowest set bit to reach 8 (1000) and reads t[8], which covers a[1..8]. Then it reaches 0 and stops. The two blocks a[9..12] and a[1..8] together form a[1..12].