Learn / Advanced structures

Fenwick tree

A Fenwick tree (binary indexed tree) keeps prefix sums that can change. Entry i stores the sum of a block ending at i whose length is the lowest set bit of i; prefix sums and point updates each touch O(log n) entries. The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.

How to recognise it

  • Prefix or range sums with point updates.
  • Counting inversions or 'how many earlier values are smaller'.
  • A segment tree would work, but less code is welcome.

Two loops

Indexes start at 1.

add(i, v):  while i <= n: f[i] += v; i += i & (-i)
sum(i):     s = 0; while i > 0: s += f[i]; i -= i & (-i); return s

Counting with it

To count, for each value, how many earlier values are smaller: walk left to right, ask sum(x - 1), then add(x, 1) (compress large values first).

Common mistakes

  • Using index 0 (the loops never move from it).
  • Forgetting to compress values before using them as indexes.

Problems

No problems listed for this pattern yet.

Check yourself

What does i & (-i) give?

How do you get the sum of a[l..r]?

Which operations does a Fenwick tree NOT handle easily?