Fenwick tree: prefix sums that can change
🌍 In real life. A shop keeps daily sales in a ledger, and the owner keeps asking "how much did we take from day 1 to day k?". A prefix-sum list (Lesson 38.1) answers in one step, until a refund changes day 3: then every running total after day 3 is wrong, and fixing them costs O(n). With many corrections and many questions, both need to be quick.
A Fenwick tree (also called a binary indexed tree) answers a prefix sum and applies a change, each in O(log n), with nothing but a list and the binary digits of the index.
The idea in one sentence: tree[i] holds the sum of a block of positions that ends at i, as long as the lowest set bit of i (i & -i); a prefix sum hops down by removing that bit each time, and an update hops up by adding it.
Its words:
- lowest set bit:
i & -i, the value of the rightmost 1 ini's binary: 6 is110, so 2; 8 is1000, so 8 - block:
tree[i]covers positionsi - (i & -i) + 1toi;tree[6]covers 5 to 6,tree[8]covers 1 to 8 - 1-based: positions start at 1, because 0 has no set bit
Step by step, the sum of days 1 to 7:
- 7 is
111:tree[7]covers day 7 alone. Take it, remove the lowest bit: 6. - 6 is
110:tree[6]covers days 5 to 6. Take it, remove the lowest bit: 4. - 4 is
100:tree[4]covers days 1 to 4. Take it: 0, stop.
Three blocks instead of seven days: one for each 1 in the binary of 7.
Changing a day. A refund of 10 on day 3 must reach every block that covers day 3: tree[3], then 3 + 1 = tree[4], then 4 + 4 = tree[8]. Adding the lowest bit jumps to the next bigger block that contains the current one.
Why it is correct. The blocks met while removing bits from i are side by side and cover 1..i exactly once, because each one starts right after where the next block (with one fewer bit) ends. The blocks met while adding bits are exactly the ones whose range contains the position.
What it costs, by counting. An index below n has at most log₂ n + 1 bits, and each hop removes one (prefix) or carries past one (update): O(log n) each. For n = 1,000,000 that is at most 20 hops, against a million for a plain loop or a rebuilt prefix list. Building with n updates costs O(n log n). A range sum is two prefix sums: prefix(hi) - prefix(lo - 1).
class Fenwick:
def __init__(self, n):
self.tree = [0] * (n + 1) # tree[0] is never used
def add(self, i, delta): # positions are 1-based
while i < len(self.tree):
self.tree[i] += delta
i += i & -i
def prefix(self, i): # the sum of positions 1..i
total = 0
while i > 0:
total += self.tree[i]
i -= i & -i
return total
def range_sum(self, lo, hi): # positions lo..hi
return self.prefix(hi) - self.prefix(lo - 1)
ledger = Fenwick(8)
for day, amount in enumerate([5, 3, 7, 2, 6, 1, 4, 8], start=1):
ledger.add(day, amount)
print(ledger.prefix(7), ledger.range_sum(3, 5))
ledger.add(3, -10) # a refund on day 3
print(ledger.prefix(7), ledger.range_sum(3, 5))Mistakes and edge cases.
- Starting at position 0.
0 & -0is 0, soadd(0, x)never moves and loops for ever. Shift 0-based positions by one. - Hopping the wrong way. A prefix sum removes the bit (
i -= i & -i); an update adds it (i += i & -i). Swapping them gives wrong sums. - Stepping by 1.
i -= 1inprefixadds up blocks that overlap, counting days several times over. - Setting instead of adding.
addtakes a change. To set day 3 to 9, add9 - old, so keep the old values in a plain list too. - Minimum and maximum. A Fenwick tree needs an undo for its operation (a range sum is a prefix minus a prefix). The minimum of a range has no such undo; the next lesson's segment tree handles it.
Quiz
What does this print?
for i in [6, 8, 12, 7]: print(i, i & -i, i - (i & -i))Which positions does tree[12] cover?
- 9 to 12
- 1 to 12
- 12 only
A prefix-sum list and a Fenwick tree both hold 1,000,000 days. Day 5 changes, then you ask a prefix sum. Roughly how many steps does each need?
- About a million for the list, about 40 for the Fenwick tree
- About 40 for both
- About a million for both
prefix(7) on the ledger should be 28, but this gives 54. Which line is wrong?
def prefix(tree, i): total = 0 while i > 0: total += tree[i] i -= 1 return total
Coding tasks
Finish the
Fenwickclass:add(i, delta)addsdeltaat 1-based positioni, andprefix(i)returns the sum of positions 1 toi, each in O(log n).Write
SalesBook(amounts)withset_day(day, amount)(day is 1-based; it replaces that day's amount) andtotal(lo, hi)(the sum of days lo..hi), using a Fenwick tree inside. Keep the current amounts in a list too, soset_dayknows the change.