Practice Discrete Math

Algorithms / Fenwick Tree Prefix Sum

Least You Need to Know: Fenwick Trees, Prefix Sums, and Low-Bit Jumps

Fenwick trees support prefix-sum queries and point updates in `O(log n)` by storing carefully chosen partial sums. The key bit trick is the low bit, which tells how large a range each index is responsible for.

The least you need to know

Key notation

lowbit(x) = x & -x size of the segment represented at index x
prefix(r) sum of positions 1 through r
range(l, r) prefix(r) - prefix(l - 1)

Tiny worked example

  • Suppose you need many updates and prefix sums over an array.
  • In a Fenwick tree, index `i` stores a sum covering the last `lowbit(i)` positions ending at `i`.
  • To query `prefix(r)`, keep adding tree values and move `r` downward by `lowbit(r)`.
  • The path length is logarithmic because each step removes the lowest set bit.

Common mistakes

How to recognize this kind of problem

Start practice