Sub topic 12
Prefix queries and point updates in a Fenwick tree
This chapter assumes you know the lowbit trick i & -i, the meaning of "the sum of the first i elements", and O(log n) cost. It also assumes the Fenwick tree uses 1-based indexing.
What each cell stores
A Fenwick tree keeps one array t of size n + 1. Index 0 is unused. Cell t[i] holds the sum of the lowbit(i) elements that end at position i. That is the range (i - lowbit(i), i].
For a = [5, 2, 7, 1, 3], the cells are:
| i | binary | lowbit | range covered | t[i] |
|---|---|---|---|---|
| 1 | 001 | 1 | a1 | 5 |
| 2 | 010 | 2 | a1..a2 | 7 |
| 3 | 011 | 1 | a3 | 7 |
| 4 | 100 | 4 | a1..a4 | 15 |
| 5 | 101 | 1 | a5 | 3 |
The implementation
class Fenwick:
# 1-indexed Fenwick tree for prefix sums.
def __init__(self, n):
self.n = n
self.t = [0] * (n + 1)
def add(self, i, delta):
while i <= self.n:
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
def range_sum(self, l, r):
return self.prefix(r) - self.prefix(l - 1)
f = Fenwick(5)
for idx, x in enumerate([5, 2, 7, 1, 3], start=1):
f.add(idx, x)
print(f.prefix(3)) # 14
print(f.range_sum(2, 4)) # 10
f.add(3, 3) # a[3] goes from 7 to 10
print(f.range_sum(2, 4)) # 13Prefix query: walking down
prefix(i) adds t[i], then removes the lowest set bit of i and repeats. Each step covers one block and jumps to the position just before that block. The blocks do not overlap, so they add up to the whole prefix.
For prefix(7), the index goes 7 (111), then 6 (110), then 4 (100), then 0. The cells are t[7] (covers a7), t[6] (covers a5..a6) and t[4] (covers a1..a4).
Point update: walking up
add(i, delta) must change every cell whose range contains position i. Adding lowbit(i) to i gives the next such cell. In the example, add(3, 3) changes t[3] and t[4]. The next index is 8, which is greater than n, so the loop ends.
A point update that sets a value needs the current value first. Compute delta = new - old, where old = range_sum(i, i), or keep a separate copy of the array.
Range sum
range_sum(l, r) subtracts two prefixes: prefix(r) - prefix(l - 1). Both calls run in O(log n). Every call to add, prefix or range_sum takes O(log n), because each step either clears or carries a bit and there are at most about log₂ n steps.
Exercise
With n = 10, which cells does prefix(10) read, and which cells does add(5, d) change?
Show answer
prefix(10): 10 is 1010, so it reads t[10], then 8 (1000) gives t[8], then 0 stops. add(5, d): 5 (0101) changes t[5], then 6 (0110) changes t[6], then 8 (1000) changes t[8], then 16 exceeds n, so it stops.