Sub topic 16
Choosing between a segment tree and a Fenwick tree
This chapter assumes you have read the earlier chapters and can write both the recursive segment tree and the Fenwick tree. Both structures answer a range query and apply a point update in O(log n). The choice depends on which operation you need, how much memory you have, and how much code you want to write.
What each structure can do
A Fenwick tree stores partial sums. A prefix query combines blocks, and a range query subtracts one prefix from another. That subtraction only works when the operation has an inverse. Sum and XOR have inverses. Min, max, and GCD do not.
A segment tree has no such limit. It needs only an associative operation and an identity element, so it handles min, max, GCD, and matrix products. It also supports lazy propagation, which lets one range update cover operations like "assign" or "add" combined with min.
| Criterion | Fenwick tree | Segment tree |
|---|---|---|
| Operations | Invertible ones (sum, XOR) | Any associative one with an identity |
| Memory | n + 1 cells | 2n (iterative) or about 4n (recursive) |
| Code size | About 10 lines | 25 to 60 lines |
| Speed | Small constant factor | Larger constant factor |
| Range update with range query | Two trees, sums only | Lazy propagation, many operations |
| k-th element search | Binary descent | Tree descent |
A decision path
A case a Fenwick tree cannot handle
Range minimum has no inverse. Knowing the minimum of a[0..4] and of a[0..1] does not tell you the minimum of a[2..4]. The iterative tree from earlier chapters works if you change the combine function and the identity. The identity for min is infinity.
class IterativeMinTree:
# Bottom-up min tree; queries use half-open [l, r).
def __init__(self, a):
self.n = len(a)
inf = float("inf")
self.t = [inf] * self.n + list(a)
for i in range(self.n - 1, 0, -1):
self.t[i] = min(self.t[2 * i], self.t[2 * i + 1])
def update(self, i, value):
i += self.n
self.t[i] = value
i >>= 1
while i >= 1:
self.t[i] = min(self.t[2 * i], self.t[2 * i + 1])
i >>= 1
def query(self, l, r):
res = float("inf")
l += self.n
r += self.n
while l < r:
if l & 1:
res = min(res, self.t[l])
l += 1
if r & 1:
r -= 1
res = min(res, self.t[r])
l >>= 1
r >>= 1
return res
mt = IterativeMinTree([5, 2, 7, 1, 3])
print(mt.query(0, 3)) # 2
print(mt.query(2, 5)) # 1
mt.update(3, 9)
print(mt.query(2, 5)) # 3Rules of thumb
- Use a Fenwick tree for sums or XOR with point updates, or for range add with range sum. It is shorter and faster, and it has fewer places to make an indexing mistake.
- Use a Fenwick tree when you need the k-th element by binary descent over non-negative counts.
- Use a segment tree when the operation is min, max, GCD, or any custom merge.
- Use a lazy segment tree when range updates must be combined with queries that are not plain sums.
Exercise
You must support "set a[i] to a value" and "report the maximum of a[l..r]" on an array of 100,000 elements. Which structure do you pick, and why can the other one not do it directly?
Show answer
Use a segment tree, such as the iterative one with max as the combine function and negative infinity as the identity. A Fenwick tree cannot do it because max has no inverse, so you cannot get the max of a[l..r] from two prefix maxima. Also, a point assignment may lower a value, and a prefix maximum stored in a Fenwick cell cannot be repaired by that update.