Fenwick Trees (DSA #16)
A segment tree solves range-sum-with-updates, but it is a lot of machinery: a \(4n\) array, recursive build, query, and update. For the specific case of prefix sums with point updates, a Fenwick tree (also called a Binary Indexed Tree, or BIT) does the job in a single array of size \(n+1\) with two tiny loops — no recursion, no lazy propagation. It is one of those rare structures that is both simpler and smaller than the general solution.
This chapter explains the clever indexing trick, the two operations, and where a Fenwick tree is the right choice over a segment tree.
The problem it solves
We want, on an array of numbers:
- point update: add \(\Delta\) to
a[i], - prefix query: the sum of
a[0..i].
Both in \(O(\log n)\). Prefix sums alone give \(O(1)\) query but \(O(n)\) update; a Fenwick tree gives both in \(O(\log n)\).
The trick: binary-indexed ranges
A Fenwick tree stores partial sums in an array tree[1..n] (1-indexed). Each index i is responsible for a range of the original array whose length is the lowest set bit of i:
\[ \text{range covered by } i = (i - \text{lowbit}(i),\ i], \qquad \text{lowbit}(i) = i \,\&\, (-i) \]
For example: lowbit(6) = 2, so tree[6] covers indices 5–6; lowbit(8) = 8, so tree[8] covers 1–8.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.7cm, minimum height=0.6cm, font=\small\bfseries}]
\foreach \i in {1,...,8} { \node[c, fill=blue!8] at (\i*0.75,0) {\i}; }
\foreach \i/\lo/\hi in {1/1/1, 2/1/2, 3/3/3, 4/1/4, 5/5/5, 6/5/6, 7/7/7, 8/1/8} {
\draw[thick, orange!75!black] (\lo*0.75-0.35,-0.55) rectangle (\hi*0.75+0.35,-0.95);
\node[font=\scriptsize, text=orange!75!black, anchor=west] at (\hi*0.75+0.4,-0.75) {tree[\i]};
}
\node[font=\rmfamily\small, text=black!60, anchor=north] at (3.4,-1.4) {each index covers a range of length lowbit(i)};
\end{tikzpicture}
Update: climb by lowbit
To add \(\Delta\) at position i, update tree[i] and then every index that covers i, which is i + lowbit(i):
class Fenwick:
def __init__(self, n):
self.n = n
self.tree = [0] * (n + 1) # 1-indexed
def add(self, i, delta): # 1-indexed position
while i <= self.n:
self.tree[i] += delta
i += i & (-i) # climb to next covering index
Starting at i, the indices i, i+lowbit(i), ... form the trail of nodes that include i. There are at most \(\log n\) of them.
Query: descend by lowbit
To sum a[1..i], accumulate tree[i] and jump to i - lowbit(i):
def prefix_sum(self, i): # sum of a[1..i]
total = 0
while i > 0:
total += self.tree[i]
i -= i & (-i) # strip the lowest set bit
return total
def range_sum(self, l, r): # sum of a[l..r]
return self.prefix_sum(r) - self.prefix_sum(l - 1)
Both loops run one iteration per set bit, so \(O(\log n)\).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.7cm, minimum height=0.6cm, font=\small\bfseries},
a/.style={->, thick}]
\foreach \i in {1,...,8} { \node[c, fill=blue!8] (n\i) at (\i*0.75,0) {\i}; }
\draw[->, very thick, orange!80!black] (n8.south) to[bend right=28] (n6.south);
\draw[->, very thick, orange!80!black] (n6.south) to[bend right=28] (n4.south);
\draw[->, very thick, orange!80!black] (n4.south) to[bend right=28] (n0.south);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (3.0,-1.1) {query(8): 8 $\to$ 6 $\to$ 4, then stop};
\end{tikzpicture}
Building from an array
You can build in \(O(n)\) by starting from the array and folding each value into its parent:
def build(nums):
n = len(nums)
fw = Fenwick(n)
for i, x in enumerate(nums, start=1):
fw.tree[i] += x
for i in range(1, n + 1):
j = i + (i & (-i))
if j <= n:
fw.tree[j] += fw.tree[i]
return fw
Or simply call add(i, nums[i-1]) for each element: \(O(n \log n)\), fine for most uses.
When a Fenwick beats a segment tree
- Prefix/range sums with point updates — the sweet spot; Fenwick is faster and simpler.
- Counting / frequency problems — maintain counts and ask “how many values \(\le x\)” (order statistics).
- Inversion counting — process right to left, count how many smaller elements have been seen via prefix sums.
- XOR prefix — XOR is invertible, so
prefix(r) ^ prefix(l-1)works too.
A Fenwick tree cannot easily do: - arbitrary range minimum/maximum with updates (no inverse), or - range updates without care.
For those, use a segment tree. The rule: if the operation has an inverse (sum, product, XOR), a Fenwick tree applies; if not (min, max, gcd), it does not.
# inversion count: how far is the array from sorted?
def count_inversions(nums):
ranked = {v: i + 1 for i, v in enumerate(sorted(set(nums)))}
fw = Fenwick(len(ranked))
inversions = 0
for x in reversed(nums):
r = ranked[x]
inversions += fw.prefix_sum(r - 1) # smaller values seen so far
fw.add(r, 1)
return inversions
Pitfalls
- Forgetting 1-indexing. Fenwick trees are 1-indexed; an off-by-one from a 0-indexed array corrupts everything.
- Using
i & -ion zero.prefix_sum(0)must return 0; the loop handles it, but do not calladd(0, ...). - Assuming it does everything a segment tree does. No inverse means no min/max range queries.
- Integer overflow. In fixed-width languages the running sums can overflow; use a wide type.
- Rebuilding per query. The tree is built once and updated in place; rebuilding defeats the purpose.
What does the lowbit represent, and why do update and query run in \(O(\log n)\)? When must you use a segment tree instead?
ASolution
lowbit(i) = i & -i is the lowest set bit, and tree[i] covers that many elements ending at i. Both loops move one set bit at a time, so they take at most the number of bits, \(O(\log n)\). Use a segment tree when the aggregation has no inverse (range min/max/gcd) or when you need range updates, which prefix differences cannot express.
Next: Disjoint Set / Union-Find (DSA #17) — tracking which elements belong together.