Segment Trees & Fenwick Trees
Answer range queries (sum, min, max) and apply updates in O(log n) — the structures behind range-query problems.
Prefix sums answer "sum of a[l..r]" in O(1) — until the array changes, which costs O(n) to rebuild. When you need both range queries and point updates, use a Fenwick tree or a segment tree: both do each in O(log n).
| Structure | Query | Update | Build | Supports |
|---|---|---|---|---|
| Plain array | O(n) | O(1) | — | anything |
| Prefix sums | O(1) | O(n) | O(n) | invertible ops (sum, xor) |
| Fenwick tree (BIT) | O(log n) | O(log n) | O(n) | sums / invertible ops |
| Segment tree | O(log n) | O(log n) | O(n) | any associative op: sum, min, max, gcd… |
Segment tree
A binary tree where each node stores the answer (say, the sum) for a segment of the array. The root covers [0, n−1]; each node splits its range in half.
A query [l, r] decomposes into at most ~2 log n fully-covered nodes. An update changes one leaf and the log n ancestors above it. Stored in an array of size 4n (or 2n for the iterative version).
class SegmentTree {
private final int n;
private final int[] t;
SegmentTree(int[] a) {
n = a.length;
t = new int[2 * n];
for (int i = 0; i < n; i++) t[n + i] = a[i]; // leaves
for (int i = n - 1; i > 0; i--) t[i] = t[2 * i] + t[2 * i + 1];
}
void update(int i, int value) { // a[i] = value
for (t[i += n] = value; i > 1; i >>= 1) t[i >> 1] = t[i] + t[i ^ 1];
}
int query(int l, int r) { // sum of a[l..r)
int res = 0;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
if ((l & 1) == 1) res += t[l++];
if ((r & 1) == 1) res += t[--r];
}
return res;
}
}class SegmentTree:
"""Iterative segment tree for range sums (replace + with min/max/gcd as needed)."""
def __init__(self, a):
self.n = n = len(a)
self.t = [0] * n + list(a)
for i in range(n - 1, 0, -1):
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
def update(self, i, value): # a[i] = value
i += self.n
self.t[i] = value
while i > 1:
i //= 2
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
def query(self, l, r): # sum of a[l:r]
res, l, r = 0, l + self.n, r + self.n
while l < r:
if l & 1: res += self.t[l]; l += 1
if r & 1: r -= 1; res += self.t[r]
l //= 2; r //= 2
return resclass SegmentTree {
private n: number;
private t: number[];
constructor(a: number[]) {
this.n = a.length;
this.t = new Array(2 * this.n).fill(0);
for (let i = 0; i < this.n; i++) this.t[this.n + i] = a[i];
for (let i = this.n - 1; i > 0; i--) this.t[i] = this.t[2 * i] + this.t[2 * i + 1];
}
update(i: number, value: number) { // a[i] = value
i += this.n;
this.t[i] = value;
for (; i > 1; i >>= 1) this.t[i >> 1] = this.t[i] + this.t[i ^ 1];
}
query(l: number, r: number): number { // sum of a[l..r)
let res = 0;
for (l += this.n, r += this.n; l < r; l >>= 1, r >>= 1) {
if (l & 1) res += this.t[l++];
if (r & 1) res += this.t[--r];
}
return res;
}
}Lazy propagation
For range updates ("add 5 to every element in [l, r]") store pending updates at internal nodes and push them down only when a query or update needs to descend. Both range update and range query stay O(log n).
Fenwick tree (Binary Indexed Tree)
A cleverly indexed array where tree[i] stores the sum of a range ending at i whose length is the lowest set bit of i (i & -i). It is shorter to write and uses exactly n + 1 slots, but only works for invertible operations like sum.
class Fenwick {
private final long[] tree;
Fenwick(int n) { tree = new long[n + 1]; } // 1-indexed
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); }
}class Fenwick:
def __init__(self, n):
self.tree = [0] * (n + 1) # 1-indexed
def add(self, i, delta): # a[i] += delta
i += 1
while i < len(self.tree):
self.tree[i] += delta
i += i & -i
def prefix(self, i): # sum of a[0..i]
i += 1
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def range(self, l, r):
return self.prefix(r) - (self.prefix(l - 1) if l else 0)class Fenwick {
private tree: number[];
constructor(n: number) { this.tree = new Array(n + 1).fill(0); }
add(i: number, delta: number) { // a[i] += delta
for (i++; i < this.tree.length; i += i & -i) this.tree[i] += delta;
}
prefix(i: number): number { // sum of a[0..i]
let s = 0;
for (i++; i > 0; i -= i & -i) s += this.tree[i];
return s;
}
range(l: number, r: number) { return this.prefix(r) - (l > 0 ? this.prefix(l - 1) : 0); }
}- Use prefix sums for static arrays; segment/Fenwick trees when values change.
- Segment trees handle any associative operation (sum, min, max, gcd) and range updates via lazy propagation.
- Fenwick trees are tiny and fast but limited to invertible operations like sums.
- Both give O(log n) query and update.
QRange minimum queries on a static array — what's the fastest structure?hard
A sparse table: precompute minimums of every power-of-two-length range in O(n log n), then answer any query in O(1) using two overlapping ranges (min is idempotent). If updates are needed, use a segment tree.
QWhat does i & -i compute and why does Fenwick rely on it?medium
It isolates the lowest set bit of i (two's complement makes -i equal to ~i + 1). Fenwick index i is responsible for a range of exactly that length, so adding or removing the lowest bit moves to the next responsible index in O(log n) steps.