Advanced Tree

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

Build segment tree for [1,3,5,7,9,11]step 1/4

// Array state

36
root
_
[1]
_
[2]
_
[3]
_
[4]
_
[5]
→ arr=[1,3,5,7,9,11]. Build root: sum = 36

// Pseudocode

1// Build segment tree — O(n)
2function build(arr, node, start, end):
3 if start == end:
4 tree[node] = arr[start] // leaf
5 return
6 mid = (start + end) / 2
7 build(arr, 2*node, start, mid) // left child
8 build(arr, 2*node+1, mid+1, end) // right child
9 tree[node] = tree[2*node] + tree[2*node+1] // merge

Complexity

Build — bottom-up sum of leavesO(n)

Linear time

Range query — touches O(log n) nodesO(log n)

Logarithmic time

Point update — update leaf + path to rootO(log n)

Logarithmic time

Space — tree array size = 4nO(n)

Linear time

Build

seg-tree-build.pseudo
1// Build segment tree — O(n)
2function build(arr, node, start, end):
3 if start == end:
4 tree[node] = arr[start] // leaf
5 return
6 mid = (start + end) / 2
7 build(arr, 2*node, start, mid) // left child
8 build(arr, 2*node+1, mid+1, end) // right child
9 tree[node] = tree[2*node] + tree[2*node+1] // merge

Range query

seg-tree-query.pseudo
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 range
4 if l <= start and end <= r:
5 return tree[node] // fully inside
6 mid = (start + end) / 2
7 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

seg-tree-update.pseudo
1// Point update — O(log n)
2function update(node, start, end, idx, val):
3 if start == end:
4 arr[idx] = val
5 tree[node] = val // update leaf
6 return
7 mid = (start + end) / 2
8 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
🔍Lazy propagation
For range updates (set all elements in [l,r] to v), propagate changes lazily: mark the range node as pending and only push down when you need to query a child. Converts range update to O(log n).
🧠Storing the tree
Store the segment tree as a flat array of size 4n. Child of node i: left = 2i, right = 2i+1. Parent of i: i/2. Same as a binary heap — no pointer overhead.

🎯 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.