Segment Trees
Answer range sum, min, max, or GCD queries AND handle point updates — both in O(log n). A brute-force approach takes O(n) per query. A segment tree drops this to O(log n) with O(n) build time.
What is a segment tree?
A segment tree stores aggregate information (sum, min or max) about ranges of an array in a binary tree, where each node covers a segment. It answers range queries such as "sum of elements 3 to 9" and handles single-element updates in O(log n), where a plain array needs O(n) for the query or a prefix-sum array needs O(n) for the update.
class SegmentTree { // range sum, point update
constructor(arr) { this.n = arr.length; this.t = Array(2 * this.n).fill(0);
arr.forEach((v, i) => (this.t[this.n + i] = v));
for (let i = this.n - 1; i > 0; i--) this.t[i] = this.t[2 * i] + this.t[2 * i + 1]; }
update(i, v) { for (this.t[i += this.n] = v; i > 1; i >>= 1) this.t[i >> 1] = this.t[i] + this.t[i ^ 1]; }
sum(l, r) { let s = 0; // [l, r)
for (l += this.n, r += this.n; l < r; l >>= 1, r >>= 1) { if (l & 1) s += this.t[l++]; if (r & 1) s += this.t[--r]; }
return s; }
}Tree structure — animated build
// Array state
// Pseudocode
Complexity
Linear time
Logarithmic time
Logarithmic time
Linear time
Build
1// Build segment tree — O(n)2function build(arr, node, start, end):3 if start == end:4 tree[node] = arr[start] // leaf5 return6 mid = (start + end) / 27 build(arr, 2*node, start, mid) // left child8 build(arr, 2*node+1, mid+1, end) // right child9 tree[node] = tree[2*node] + tree[2*node+1] // merge
Range query
1// Range sum query — O(log n)2function query(node, start, end, l, r):3 if r < start or end < l: return 0 // out of range4 if l <= start and end <= r:5 return tree[node] // fully inside6 mid = (start + end) / 27 left = query(2*node, start, mid, l, r)8 right = query(2*node+1, mid+1, end, l, r)9 return left + right
Point update
1// Point update — O(log n)2function update(node, start, end, idx, val):3 if start == end:4 arr[idx] = val5 tree[node] = val // update leaf6 return7 mid = (start + end) / 28 if idx <= mid:9 update(2*node, start, mid, idx, val)10 else:11 update(2*node+1, mid+1, end, idx, val)12 tree[node] = tree[2*node] + tree[2*node+1] // re-merge
🎯 Quick Check
How many nodes does a segment tree for an array of 8 elements have?
Segment Trees: summary
Key points
- Build O(n), query O(log n), update O(log n), memory O(n).
- Lazy propagation supports range updates ("add 5 to elements 2..8") in O(log n).
- For prefix sums with point updates only, a Fenwick tree is simpler.
Frequently asked questions
›Segment tree vs Fenwick tree?
A Fenwick tree is shorter and lighter but mainly handles prefix sums. A segment tree handles any associative operation (min, max, gcd) and range updates.