Fenwick trees and dynamic prefix sums
A Fenwick tree answers prefix-sum queries quickly while allowing individual values to change.
How it works
For index 6, the least significant set bit says that entry covers indices 5 and 6. Moving to index 4 reads the summary for indices 1 through 4. Together they cover exactly the requested prefix. For a range sum, subtract the prefix before the range from the prefix at its end.
Walk through an example
Each stored entry covers a range whose size is its lowest set bit. In a one-based query, add the current entry and subtract that bit to move to the preceding range.
What to watch for
Use one-based internal indexes. An update at index zero would add zero to itself and never move.
Code example
def prefix_sum(tree, i):
total = 0
while i > 0:
total += tree[i]
i -= i & -i
return totalCheck your understanding
Which indexes are read using i -= i & -i?
See the example and explanation
- Worked example
- Given
A query begins at one-based index 6. - Answer
6, then 4
The lowest set bit of 6 is 2, so the next index is 4. The lowest set bit of 4 is 4, which moves the query to 0.