Video in progress
If range-sum queries and element updates come mixed on an array, why isn't a prefix sum enough, and what do you use?
A prefix sum makes a query O(1), but a single update requires an O(n) recomputation. A Fenwick tree (BIT) or a segment tree makes both O(log n). A Fenwick tree is short and fast, while a segment tree is more flexible for min/max and range updates.
📖 Answer
Do the math: 10⁵ elements, 10⁵ mixed operations. With a prefix sum, the worst case is 10¹⁰ operations. With a Fenwick tree, about 3.4 × 10⁶.
A Fenwick tree is a modest 20-line structure:
final class Fenwick {
private final long[] tree; // 1-indexed
Fenwick(int n) { tree = new long[n + 1]; }
void add(int i, long delta) { // a[i] += delta
for (i++; i < tree.length; i += i & -i) tree[i] += delta;
}
long prefix(int i) { // sum of a[0..i]
long s = 0;
for (i++; i > 0; i -= i & -i) s += tree[i];
return s;
}
long range(int l, int r) { return prefix(r) - (l > 0 ? prefix(l - 1) : 0); }
}
i & -i is the lowest set bit. Each cell stores the sum of a range whose length is that bit.
Cases where a Fenwick tree isn't enough:
- min/max queries: these operations can't be subtracted, and a Fenwick tree relies on prefix differences. You need a segment tree;
- range updates ("add +5 to everything from 3 to 900"): a segment tree with lazy propagation;
- min on an immutable array: a sparse table, O(1) per query.
Where do you need it in a real system? For example, in a leaderboard, "what rank is this user": a Fenwick tree over scores, updated in O(log n) when a score changes. But to be honest, on prod this is usually solved with a Redis sorted set (a skip list) or a DB index. Writing a Fenwick tree ourselves is worth it only when the data is in memory and on a very hot path.
Sign up to mark studied questions and save your progress.