Fenwick Trees for Dynamic Prefix Sums
Decompose a prefix into low-bit blocks and derive the update route through the represented ranges.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 2
- Reading time
- 1 min
In this article2 chapters
A stored cell describes a suffix of a prefix
Use positive indices. Entry \(F[i]\) holds the sum of the last \(\operatorname{lowbit}(i)\) data items ending at \(i\), where the low bit is the largest power of two dividing \(i\). To query a prefix ending at \(i\), add that entry and subtract its low bit to expose the remaining prefix. For \(i=13\), the query visits \(13,12,8\) and covers disjoint intervals \(13\), \(9\) through \(12\), and \(1\) through \(8\).
A point update visits every stored range that contains it
After adding a delta at position \(i\), add the delta to \(F[i]\), then advance by its low bit and repeat through the valid range. This climbs to the next containing block. The low-bit scale increases along the route, giving logarithmic steps. A range sum uses the difference of two prefixes. Segment trees support other associative operations and lazy updates. Order-statistic trees handle evolving sets whose keys do not already occupy dense integer indices.[1]