A segment tree and a Fenwick tree (Binary Indexed Tree, BIT) both answer range queries (e.g. sum over [l, r]) and point updates in O(log n), versus O(n) for a naive scan or O(n) updates for a prefix-sum array.
A segment tree and a Fenwick tree (Binary Indexed Tree, BIT) both answer range queries (e.g. sum over [l, r]) and point updates in O(log n), versus O(n) for a naive scan or O(n) updates for a prefix-sum array.
Array + many "sum of range [l,r]" and "update index i" calls:
naive prefix sums: query O(1) but UPDATE is O(n)
segment/Fenwick: query O(log n) AND update O(log n)
class Fenwick:
def __init__(self, n):
self.t = [0]*(n+1)
def update(self, i, delta): # O(log n)
i += 1
while i < len(self.t):
self.t[i] += delta
i += i & (-i) # jump to next responsible node
def prefix(self, i): # sum of [0..i], O(log n)
i += 1; s = 0
while i > 0:
s += self.t[i]
i -= i & (-i)
return s
def range_sum(self, l, r):
return self.prefix(r) - self.prefix(l-1)
A segment tree stores an aggregate per array segment in a binary tree, supporting any associative operation (sum, min, max, gcd) and, with lazy propagation, range updates too.
[0..7] sum
/ \
[0..3] [4..7]
/ \ / \
[0..1][2..3] [4..5][6..7] ... down to single elements
| Fenwick (BIT) | Segment tree | |
|---|---|---|
| Query / update | O(log n) | O(log n) |
| Space | O(n) | O(2n) |
| Operations | sums (invertible) | any associative op |
| Range updates | harder | easy (lazy propagation) |
| Code size | tiny | larger |
These structures make "update a value, then query an aggregate over a range" fast — essential for competitive programming, analytics windows, and interval problems.
Choosing between them is a trade-off: a Fenwick tree is tiny and fast for sums, while a segment tree is more flexible for min/max/range-update workloads.