Segment tree
hard 24 minA segment tree is a binary tree in which every node stores the answer (sum, min, max, GCD) for one range of an array.
Video lesson · Chapter 1 of 8
Room occupancy board
Segment trees in 75 seconds
1:22Reel
How it works
Step through the idea, or press Play.
Split ranges in half. The root owns the whole array; each node's range is cut at mid until every leaf holds one element
Understand it
Start here
What a segment tree is
Recap: binary trees
Every node has at most two children and a complete tree has about levels. See binary trees.
Recap: recursion
Build, query and update are all recursive: a base case at the leaf and a combine step on the way back. See recursion.
Recap: prefix sums
range sums on a fixed array, but one change costs . See prefix sums.
A segment tree is a binary tree built over an array. Each node stores the answer for one contiguous range (segment) of the array: the root covers everything, its children cover the two halves, and each leaf covers a single element. It answers range queries such as sum, min, max or GCD and applies point updates, both in .
Range queries
Sum, min, max or GCD of any in .
Point updates
Change any element and fix the stored answers in .
Both fast at once
Prefix sums or a plain array make one operation fast and the other . This makes both logarithmic.
Motivation
Why not a loop or prefix sums?
Take and a stream of two kinds of request: sum of $a[l..r]$ and set $a[i] = v$. Each familiar tool is fast at one and slow at the other.
| Approach | Range query | Point update | Good for |
|---|---|---|---|
| Plain loop over the array | Rare queries, small arrays | ||
| Prefix sums: | to fix | Static data, no updates | |
| Segment tree | Queries and updates mixed |
Cost of n queries plus n updates
Anatomy
Every node owns a range
A node stores three things: its value (the merged answer) and the left and right ends of its range. In the usual array layout the range is not stored at all; it is passed down the recursion as lo and hi.
Sum tree over [1, 3, 5, 7, 9, 11, 13, 15]
Array layout (root at index 1)
For node at index i | Index | Range |
|---|---|---|
| Root | 1 | |
| Left child | 2 * i | with |
| Right child | 2 * i + 1 | |
| Parent | i // 2 | the range that contains this one |
Operation 1
Building it bottom-up
build(node, lo, hi)
Build is linear
class SegmentTree: def __init__(self, a): self.n = len(a) self.tree = [0] * (4 * self.n) self._build(a, 1, 0, self.n - 1) def _build(self, a, node, lo, hi): if lo == hi: self.tree[node] = a[lo] return mid = (lo + hi) // 2 self._build(a, 2 * node, lo, mid) self._build(a, 2 * node + 1, mid + 1, hi) self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1] def query(self, l, r, node=1, lo=0, hi=None): if hi is None: hi = self.n - 1 if r < lo or hi < l: # no overlap return 0 if l <= lo and hi <= r: # full overlap return self.tree[node] mid = (lo + hi) // 2 # partial overlap return (self.query(l, r, 2 * node, lo, mid) + self.query(l, r, 2 * node + 1, mid + 1, hi)) def update(self, i, val, node=1, lo=0, hi=None): if hi is None: hi = self.n - 1 if lo == hi: self.tree[node] = val return mid = (lo + hi) // 2 if i <= mid: self.update(i, val, 2 * node, lo, mid) else: self.update(i, val, 2 * node + 1, mid + 1, hi) self.tree[node] = self.tree[2 * node] + self.tree[2 * node + 1]st = SegmentTree([1, 3, 5, 7, 9, 11, 13, 15])print(st.tree[1]) # 64print(st.query(1, 4)) # 24st.update(2, 10) # a[2]: 5 -> 10print(st.query(1, 4)) # 29print(st.tree[1]) # 69Operation 2
Range query: three cases
To answer sum(1, 4) , start at the root and compare each node's range with the query . Exactly one of three cases applies.
No overlap
or . The node is useless: return the identity (0 for sum).
Full overlap
and . Return the stored value and do not go deeper.
Partial overlap
Anything else. Ask both children and merge their answers.
query(node, lo, hi, l, r)
Proof
Why a query is O(log n)
Look at one level of the tree. Its nodes are disjoint ranges side by side. A node can only be partial if the query's left edge or right edge falls strictly inside it, and each edge falls inside at most one node per level.
At most 2 nodes split per level
Total work
Operation 3
Point update: one path up
Setting (it was 5) only invalidates the nodes whose range contains index 2: , , and . Walk down to the leaf, change it, and recompute each ancestor on the way back: , , , .
update(node, lo, hi, i, val)
- 1[2]5 → 10
- 2[2-3]10 + 7 = 17
- 3[0-3]4 + 17 = 21
- 4[0-7]21 + 48 = 69
Siblings such as [0-1] and [4-7] are read but never rewritten.
Update cost is the height
Space
Why the array has 4n slots
With the root at 1 and children at and , a tree of height can use indexes up to . When is not a power of two, some branches are deeper than others and leave gaps, so slots are not enough.
The 4n bound
| n | Largest index used | 2n | 4n | 2n enough? |
|---|---|---|---|---|
| 5 | 9 | 10 | 20 | yes |
| 6 | 13 | 12 | 24 | no |
| 8 | 15 | 16 | 32 | yes |
| 100 | 253 | 200 | 400 | no |
Variants
Sum, min, max, GCD: change the merge
| Query | Parent value | No-overlap identity | On [5, 2, 8, 6, 1, 9, 4, 7], range [2, 6] |
|---|---|---|---|
| Range sum (RSQ) | left + right | ||
| Range min (RMQ) | min(left, right) | ||
| Range max | max(left, right) | ||
| Range GCD | gcd(left, right) | (since ) |
What makes a merge work
import mathclass SegTree: def __init__(self, a, merge, identity): self.n, self.f, self.e = len(a), merge, identity self.t = [identity] * (4 * self.n) self._build(a, 1, 0, self.n - 1) def _build(self, a, k, lo, hi): if lo == hi: self.t[k] = a[lo] return mid = (lo + hi) // 2 self._build(a, 2 * k, lo, mid) self._build(a, 2 * k + 1, mid + 1, hi) self.t[k] = self.f(self.t[2 * k], self.t[2 * k + 1]) def query(self, l, r, k=1, lo=0, hi=None): hi = self.n - 1 if hi is None else hi if r < lo or hi < l: return self.e if l <= lo and hi <= r: return self.t[k] mid = (lo + hi) // 2 return self.f(self.query(l, r, 2 * k, lo, mid), self.query(l, r, 2 * k + 1, mid + 1, hi))a = [5, 2, 8, 6, 1, 9, 4, 7]print(SegTree(a, lambda x, y: x + y, 0).query(2, 6)) # 28print(SegTree(a, min, float("inf")).query(2, 6)) # 1print(SegTree(a, max, float("-inf")).query(2, 6)) # 9print(SegTree(a, math.gcd, 0).query(2, 3)) # gcd(8, 6) = 2Choosing
Segment tree vs prefix sums vs Fenwick tree
| Prefix sums | Fenwick tree (BIT) | Segment tree | |
|---|---|---|---|
| Build | |||
| Range query | |||
| Point update | |||
| Range min / max | no | not with updates in general | yes |
| Range update | difference array, offline | with two trees, sums only | yes, lazy propagation |
| Space and code | slots, 3 lines | slots, about 10 lines | slots, about 30 lines |
Which structure?
Use a segment tree when
- Range queries (sum, min, max, GCD) and point updates are both frequent.
- The merge is not invertible, so prefix tricks fail (min, max, GCD).
- Whole ranges are updated at once (with lazy propagation).
- A competitive programming problem has operations on elements.
Use something simpler when
- Nothing ever changes: prefix sums, or a sparse table for min and max.
- Only sums with point updates: a Fenwick tree is shorter.
- The array is small: a loop is fast enough and hard to get wrong.
- You only read single elements: direct array access.
Range updates
Lazy propagation
Now suppose the request is add $v$ to every element of $a[l..r]$. Doing point updates costs . Lazy propagation applies the change to the same fully covered nodes a query would use, and leaves a note (a lazy tag) saying "my children still owe ". The note is pushed down only when someone later needs to go below that node.
range_add(node, lo, hi, l, r, v)
Applying a pending add to a whole range
class LazySegTree: def __init__(self, n): self.n = n self.t = [0] * (4 * n) # sums self.lz = [0] * (4 * n) # pending add for the children def _apply(self, k, lo, hi, v): self.t[k] += v * (hi - lo + 1) self.lz[k] += v def _push(self, k, lo, hi): if self.lz[k]: mid = (lo + hi) // 2 self._apply(2 * k, lo, mid, self.lz[k]) self._apply(2 * k + 1, mid + 1, hi, self.lz[k]) self.lz[k] = 0 def add(self, l, r, v, k=1, lo=0, hi=None): hi = self.n - 1 if hi is None else hi if r < lo or hi < l: return if l <= lo and hi <= r: self._apply(k, lo, hi, v) return self._push(k, lo, hi) mid = (lo + hi) // 2 self.add(l, r, v, 2 * k, lo, mid) self.add(l, r, v, 2 * k + 1, mid + 1, hi) self.t[k] = self.t[2 * k] + self.t[2 * k + 1] def total(self, l, r, k=1, lo=0, hi=None): hi = self.n - 1 if hi is None else hi if r < lo or hi < l: return 0 if l <= lo and hi <= r: return self.t[k] self._push(k, lo, hi) mid = (lo + hi) // 2 return self.total(l, r, 2 * k, lo, mid) + self.total(l, r, 2 * k + 1, mid + 1, hi)s = LazySegTree(8)s.add(2, 5, 3) # a = [0, 0, 3, 3, 3, 3, 0, 0]s.add(4, 7, 1) # a = [0, 0, 3, 3, 4, 4, 1, 1]print(s.total(0, 7)) # 16print(s.total(3, 4)) # 7Recap
Key takeaways
Key points
- Each node stores the merged answer for one range; children split it at ; leaves are single elements.
- Root at index 1, children at and ; allocate slots for the recursive layout.
- Build is ; range query and point update are because at most 4 nodes per level are visited and an update walks one path.
- Query cases: no overlap returns the identity, full overlap returns the node, partial overlap recurses into both children.
- Sum, min, max and GCD differ only in the merge and its identity (0, , , 0).
- Static data: prefix sums. Sums with updates: Fenwick tree or segment tree. Min or max with updates, or range updates: segment tree (with lazy propagation).