Fenwick Trees in Depth
Lowest set bits, range updates and 2-D Fenwick trees.
A Fenwick tree is an array of numbers and two loops that add or subtract the lowest set bit of an index. Yet it answers prefix sums under updates in , finds the -th smallest stored value without a binary search over queries, supports range updates with range sums, and extends to any number of dimensions. All of it follows from one fact about binary numbers.
What you’ll learn
- Prove that the ranges read by a prefix query partition , and that an update visits exactly the ranges that contain its position.
- Build a Fenwick tree in , and find the smallest position whose prefix sum reaches in by binary lifting.
- Derive range updates with range sums from two Fenwick trees, and extend the structure to two dimensions.
- Place the structure in its history (Ryabko; Fenwick) and against the cell-probe lower bound for dynamic prefix sums.
Why the lowest set bit works
Prefix. Clearing the lowest set bit of gives , exactly the left end of 's range, so the ranges read by the walk meet end to end and stop at 0, one per 1-bit of :
Update. Let with odd. A larger dyadic interval containing 's range, of length , ends at the first multiple of at or after . That multiple is for every up to the lowest set bit of , and the interval is a Fenwick range exactly when equals that bit. So the next range up the chain belongs to , and the update walk visits precisely the entries that contain the updated position:
Cost. The prefix walk removes a 1-bit per step; the update walk strictly raises the lowest set bit per step. Either way:
In a Fenwick tree over positions, how many entries does a point update at position 1 write?
Show the answer
10 writes
The path is , and the next index, , exceeds 1000: ten writes. Each step doubles the lowest set bit, so no update on 1000 positions can write more than 10 entries.
Linear-time construction and binary lifting
Inserting values one by one costs . Linear time is possible because each entry has a parent, , the next range up its chain, and the children of , namely , cover exactly. So is plus its children's entries, and a single left-to-right pass, adding each finished entry into its parent, builds them all.
def build(a): # a[1..n] (a[0] unused) -> Fenwick array in O(n)
n = len(a) - 1
f = a[:] # f[p] starts as a[p]
for p in range(1, n + 1):
q = p + (p & -p) # the parent: next range containing p's range
if q <= n:
f[q] += f[p] # f[p] is complete: all its children are < p
return f
def find(f, k): # smallest p with prefix(p) >= k; needs a[i] >= 0
n = len(f) - 1
pos, step = 0, 1 << (n.bit_length() - 1) # largest power of two <= n
while step:
if pos + step <= n and f[pos + step] < k:
pos += step # f[pos + step] covers exactly (pos, pos + step]
k -= f[pos]
step >>= 1
return pos + 1 # prefix(pos) < k <= prefix(pos + 1); n + 1 if nonefind is binary search done inside the tree: one entry per bit, , against for a binary search that calls prefix at every probe. It needs non-negative values, so that prefix sums never decrease.
The -th smallest of a dynamic multiset. Store, at position , how many copies of the value are present (after coordinate compression if values are large). Insertion and deletion are add(v, ±1), and the -th smallest value is find(f, k). For the multiset , find returns 1, 3, 3, 7, 9 for : an order-statistic structure in a dozen lines, when the values come from a small universe.
During find, why does cover exactly the positions ?
- Because is a sum of larger powers of two, hence a multiple of , so
- Because is always 1 at the end
- Because prefix sums are non-decreasing
- Because was built in time
Show the answer
A. Because is a sum of larger powers of two, hence a multiple of , so
The search adds powers of two in decreasing order, so when it considers , consists of larger powers only and is a multiple of . Then has lowest set bit , and its range is : one read tells whether the answer lies beyond .
Range updates with range sums: two trees
A Fenwick tree over the difference array , with , already turns range updates into two point updates and point queries into prefix sums. Range sums need the prefix sums of itself, and one more tree recovers them.
Expand the prefix sum of in terms of : the difference contributes to , that is, times.
Split off the part that depends on :
So keep two Fenwick trees, over and over . Adding to changes by and by , which is four point updates:
Every operation is a constant number of Fenwick operations, each:
class RangeFenwick: # range add, range sum; positions 1..n
def __init__(self, n):
self.n, self.b1, self.b2 = n, [0] * (n + 2), [0] * (n + 2)
def _add(self, f, p, d):
while p <= self.n:
f[p] += d; p += p & -p
def _pre(self, f, p):
s = 0
while p > 0:
s += f[p]; p -= p & -p
return s
def range_add(self, l, r, v): # a[l..r] += v
self._add(self.b1, l, v); self._add(self.b1, r + 1, -v)
self._add(self.b2, l, l * v); self._add(self.b2, r + 1, -(r + 1) * v)
def range_sum(self, l, r): # a[l] + ... + a[r]
S = lambda p: (p + 1) * self._pre(self.b1, p) - self._pre(self.b2, p)
return S(r) - S(l - 1)Half the memory of a lazy segment tree and no recursion. It works because addition is invertible and the update's effect on prefix sums is a linear function of ; range assignment or range minimum need lazy propagation instead.
Think first On an all-zero array with , add 5 to positions 3 to 6. What do and hold, and what is ?
holds at 3 and at 7, so . holds at 3 and at 7, so . Then : positions 3 and 4 hold 5 each. Likewise , four positions of 5.
Two dimensions, history and limits
In two dimensions, covers the rectangle , and both loops simply nest. A point update and a prefix-rectangle sum cost , any rectangle is four prefix rectangles by inclusion–exclusion, and dimensions cost per operation. The price is memory; when all points and queries are known in advance, sorting by one coordinate and keeping a one-dimensional Fenwick tree over the other answers the same counting queries in time with linear memory.
class Fenwick2D: # point add, rectangle sum: O(log n log m)
def __init__(self, n, m):
self.n, self.m = n, m
self.f = [[0] * (m + 1) for _ in range(n + 1)]
def add(self, x, y, d):
i = x
while i <= self.n:
j = y
while j <= self.m:
self.f[i][j] += d; j += j & -j
i += i & -i
def prefix(self, x, y): # sum over [1..x] x [1..y]
s, i = 0, x
while i > 0:
j = y
while j > 0:
s += self.f[i][j]; j -= j & -j
i -= i & -i
return sA rectangle is prefix(x2, y2) - prefix(x1 - 1, y2) - prefix(x2, y1 - 1) + prefix(x1 - 1, y1 - 1).
Can anything beat ? In the cell-probe model, which charges only for memory accesses and so covers every algorithm, maintaining prefix sums of word-sized numbers under updates needs amortized time per operation, even with randomization (Pătraşcu & Demaine, 2004). The Fenwick tree is optimal up to a constant factor. With updates the bound drops to ; the lessons 2-D Prefix Sums & Inclusion–Exclusion and Augmented Search Trees discuss both bounds.
Key takeaways
- covers the dyadic interval , and any two such intervals are nested or disjoint. Clearing lowest set bits splits a prefix into ranges; adding them climbs the chain of ranges that contain a position. Both walks are .
- Passing each finished entry to its parent builds the tree in ; binary lifting finds the smallest with in , because stays a multiple of .
- Range additions with range sums take two trees: , so each update is four point updates and each sum two prefix pairs. In dimensions the loops nest, per operation.
- Ryabko (1989) and Fenwick (1994) invented the structure for adaptive arithmetic coding, and the cell-probe lower bound of Pătraşcu and Demaine shows that its is optimal for word-sized updates.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does p & -p isolate the lowest set bit of in two's complement?
- Because is with every bit flipped, so the AND keeps the bits where both are 1
- Because agrees with on the lowest set bit and the zeros below it, and is the complement of above it
- Because the AND of any two numbers is a power of two
- Because the sign bit of masks every bit but one
Show the answer
B. Because agrees with on the lowest set bit and the zeros below it, and is the complement of above it
has 1s where has its trailing zeros and a 0 at its lowest set bit; adding 1 carries through those 1s and sets that bit. Above it nothing changes, so is the complement of there, and the AND keeps exactly the lowest set bit. For : , and .
With two Fenwick trees, over and over , which point updates implement "add to "?
- : at ; : at
- : at every position from to
- : at and at ; : at and at
- : at and at ; : at and at
Show the answer
D. : at and at ; : at and at
The update changes by and by , and stores , so its changes are and . Then is correct for every .
In a Fenwick tree over positions, which entries does an update at position 5 write?
- 5, 4
- 5, 7, 15
- 5, 6, 8, 16
- 5, 10, 20
Show the answer
C. 5, 6, 8, 16
, adding the lowest set bit each time. These are exactly the entries whose ranges contain position 5: , , and .
You need the smallest position whose prefix sum reaches , in a Fenwick tree over non-negative values. What does binary lifting cost, compared with binary search over prefix calls?
- against : lifting reads one entry per bit instead of a whole prefix per probe
- Both cost
- against
- Lifting is , since it may scan every entry
Show the answer
A. against : lifting reads one entry per bit instead of a whole prefix per probe
Binary search makes probes, each a prefix query costing . Lifting walks the bits from high to low and reads a single entry per bit, keeping the sum of everything to the left of in hand.
Further reading
- P. M. Fenwick, "A new data structure for cumulative frequency tables," Software: Practice and Experience 24(3) (1994), 327–336.
- B. Ya. Ryabko, "A fast on-line adaptive code," IEEE Transactions on Information Theory 38(4) (1992), 1400–1404.
- M. Pătraşcu & E. D. Demaine, "Tight bounds for the partial-sums problem," Proceedings of the 15th ACM-SIAM Symposium on Discrete Algorithms (SODA) (2004), 20–29.
- CP-Algorithms, Fenwick Tree.