Segment trees
Implement a segment tree for range sum, min or max queries with point updates.
By Invicly Tech, , in Data Structures & Algorithms. About 14 minutes to read.
In short
A segment tree is a binary tree where each node stores an aggregate, such as sum, min or max, for a segment of the array. Queries combine O(log n) nodes and point updates refresh one root-to-leaf path. Lazy propagation extends it to range updates by deferring work to children until needed.
Explained simply
A segment tree answers questions like "what is the smallest value between position 100 and 900?" quickly, even while the values keep changing. Picture a sports tournament bracket: players stand at the bottom, and each match sends one result upward. Each node in the tree knows the answer (sum, min or max) for its group of elements.
The root covers the whole array. It splits into a left half and a right half, and each half splits again, until every node covers a single element. For n elements there are about 2n nodes and the height is about log2 n.
To answer a range question, you pick a few nodes that together cover exactly that range and combine their answers. To change one element, you change its leaf and recompute every node on the path up to the root. Both cost about log n steps.
There is also a trick called lazy propagation. It lets you do things like "add 5 to every element from 100 to 900" quickly, by leaving a note on a few big nodes instead of touching every element.
Press Play on a diagram to walk through it one step at a time.
- [0..1] = 3
- [0] = 2
- [1] = 1
- [2..3] = 8
- [2] = 5
- [3] = 3
- Step 1Set leaf [2]
5 becomes 7.
- Step 2Parent [2..3]
7 + 3 = 10.
- Step 3Root [0..3]
3 + 10 = 13.
- Step 4Done
One node per level touched.
- k separate updates
- O(k log n) time
- Simple code
- Fine when k is tiny
- One range update
- O(log n) time
- Extra lazy array
- Push before visiting children
In depth
Layout, building and the 4n rule
The usual recursive version stores nodes in an array. Node 1 is the root. Node v has children 2v and 2v + 1. If v covers [lo, hi], let mid = (lo + hi) // 2: the left child covers [lo, mid] and the right child covers [mid + 1, hi]. A node with lo == hi is a leaf holding one array value.
Build recursively: build both children, then set t[v] = combine(t[2v], t[2v + 1]). There are 2n - 1 real nodes and each is visited once, so building is O(n).
Why allocate 4n slots and not 2n? When n is not a power of two the tree is not perfectly balanced, and the numbering skips slots, so indexes can go beyond 2n. They always stay below 4n, which is why 4n is the safe size. The iterative bottom-up version stores leaves at t[n..2n-1] and needs only 2n.
- Children of v: 2v and 2v + 1
- Build O(n), height about ceil(log2 n)
- Recursive: 4n slots; iterative: 2n slots
How a range query picks its nodes
query(l, r) at node v covering [lo, hi] has three cases. No overlap (r < lo or hi < l): return the identity value, such as 0 for sum. Full overlap (l <= lo and hi <= r): return t[v] without going deeper. Partial overlap: ask both children and combine the results.
The key fact: at each level of the tree, at most 4 nodes are visited, and at most 2 of them recurse further. The ones fully inside stop at once. So a query costs O(log n) no matter how wide the range is.
For example, on 8 elements, the range [1, 5] is answered by exactly three nodes: [1], [2..3] and [4..5]. A point update is simpler: walk down to the leaf, change it, and recompute each parent on the way back up, touching one node per level.
- [0..3] partial
- [0..1] partial, use [1]
- [2..3] fully inside, used
- [4..7] partial
- [4..5] fully inside, used
- [6..7] no overlap, skipped
Beyond sums: min, max, gcd and custom nodes
A segment tree works for any associative operation, meaning (a op b) op c equals a op (b op c). You also need an identity value for the no-overlap case: 0 for sum and xor, 1 for product, +infinity for min, -infinity for max, and 0 for gcd, since gcd(0, x) = x.
The operation does not have to be commutative, as long as you always combine the left child before the right one. That allows things like matrix products over a range.
Nodes can also store several numbers. For "maximum subarray sum inside [l, r]", each node keeps four values: total, best prefix, best suffix and best overall. Combining two children: total adds up, best prefix is max(left prefix, left total + right prefix), best suffix is the mirror, and best is max(left best, right best, left suffix + right prefix). The tree code stays the same; only combine changes.
Lazy propagation for range updates
Adding d to every element in [l, r] one by one costs O(k log n) for k elements. Lazy propagation makes it O(log n). Each node gets a second field, lazy, meaning "this much still needs to be added to every element below me".
During a range add, when a node is fully inside [l, r], update its own value right away (for a sum tree, sum += d * (hi - lo + 1)), add d to its lazy field, and stop. Do not visit its children. When a later query or update needs to go below a node, first push: apply that node's lazy value to both children and reset it to 0. Then recurse, and on the way back recompute the node from its children.
Range add on a min or max tree is simpler: the node value just increases by d. Range assign needs a different tag, and mixing assign and add tags needs a clear rule for which applies first.
- 1No overlap?
Return, nothing to do.
- 2Fully inside?
sum += d * length, lazy += d, return.
- 3Push
Give this node's lazy to both children.
- 4Recurse
Left child, then right child.
- 5Pull
sum = left sum + right sum.
Choosing the right range structure
Do not reach for a segment tree first. If the array never changes, a prefix sum array gives range sums in O(1) after O(n) setup. For range minimum on a static array, a sparse table gives O(1) queries after O(n log n) setup, because min can overlap two blocks safely.
If values change and you only need sums, a Fenwick tree is shorter and faster. Use a segment tree when you need min, max, gcd or a custom combine with updates, or range updates with range queries.
In Python, recursion has real overhead. The iterative bottom-up tree (leaves at n to 2n - 1, parents computed downward from n - 1) is usually several times faster than the recursive one. For lazy propagation most people still use recursion, but keep the code tight and avoid creating objects inside the loop.
- Static sums: prefix sums
- Static min or max: sparse table
- Sums with point updates: Fenwick tree
- Min, max, custom or range updates: segment tree
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Build the tree recursively~50m
- 2Answer range queries~50m
- 3Apply point updates~50m
- 4Generalise to min, max and gcd~50m
- 5Understand lazy propagation for range updates~50m
Key points
- Build O(n), query O(log n), point update O(log n).
- Memory about 4n for a recursive array-based tree.
- Works for any associative operation: sum, min, max, gcd.
- Lazy propagation gives O(log n) range updates.
Key terms
Tap a card to flip it. 0/3 known
Examples
class SegTree: # iterative sum tree
def __init__(self, a):
self.n = len(a)
self.t = [0] * self.n + list(a)
for i in range(self.n - 1, 0, -1):
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
def query(self, l, r): # sum of a[l:r], O(log n)
s, l, r = 0, l + self.n, r + self.n
while l < r:
if l & 1: s += self.t[l]; l += 1
if r & 1: r -= 1; s += self.t[r]
l //= 2; r //= 2
return sA point update sets t[n + i] and recomputes each parent up to the root.
Range minimum on a = [5, 2, 8, 6, 3, 7]
Step 1: build. Leaves hold the values; [0..2] holds min(5, 2, 8) = 2, [3..5] holds min(6, 3, 7) = 3, and the root holds 2. Step 2: query(2, 4). The root is a partial overlap, so ask both halves. In [0..2], only [2] is inside, giving 8. In [3..5], the left part [3..4] is fully inside, giving 3, and [5] has no overlap, giving infinity. Step 3: combine: min(8, 3) = 3. A point update would set a leaf and recompute min on the way up.
INF = float("inf")
class MinTree:
def __init__(self, a):
self.n = len(a); self.t = [INF] * (4 * self.n); self._build(a, 1, 0, self.n - 1)
def _build(self, a, v, lo, hi):
if lo == hi: self.t[v] = a[lo]; return
mid = (lo + hi) // 2
self._build(a, 2 * v, lo, mid); self._build(a, 2 * v + 1, mid + 1, hi)
self.t[v] = min(self.t[2 * v], self.t[2 * v + 1])
def query(self, l, r, v=1, lo=0, hi=None): # min of a[l..r], O(log n)
if hi is None: hi = self.n - 1
if r < lo or hi < l: return INF
if l <= lo and hi <= r: return self.t[v]
mid = (lo + hi) // 2
return min(self.query(l, r, 2 * v, lo, mid), self.query(l, r, 2 * v + 1, mid + 1, hi))Lazy range add on a sum tree
Start with 8 zeros and call add(2, 6, 5). At the root [0..7] the range is partial, so push (nothing pending) and recurse. [0..3] is partial: [0..1] has no overlap, [2..3] is fully inside, so its sum becomes 5 * 2 = 10 with lazy 5, and we stop there. [4..7] is partial: [4..5] is fully inside (sum 10, lazy 5), and [6..7] goes one level deeper to update [6]. Parents then pull their sums: the root becomes 25. Only a handful of nodes were touched, not all five elements one by one.
class LazySum:
def __init__(self, n): self.n, self.s, self.lz = n, [0] * (4 * n), [0] * (4 * n)
def _apply(self, v, lo, hi, d): self.s[v] += d * (hi - lo + 1); self.lz[v] += d
def _push(self, v, lo, mid, hi):
if self.lz[v]:
self._apply(2 * v, lo, mid, self.lz[v]); self._apply(2 * v + 1, mid + 1, hi, self.lz[v])
self.lz[v] = 0
def add(self, l, r, d, v=1, lo=0, hi=None): # add d to a[l..r], O(log n)
hi = self.n - 1 if hi is None else hi
if r < lo or hi < l: return
if l <= lo and hi <= r: return self._apply(v, lo, hi, d)
mid = (lo + hi) // 2; self._push(v, lo, mid, hi)
self.add(l, r, d, 2 * v, lo, mid); self.add(l, r, d, 2 * v + 1, mid + 1, hi)
self.s[v] = self.s[2 * v] + self.s[2 * v + 1]
# A range-sum query has the same shape: push before recursing into children.Quick reference
- Recursive layout: root is node 1, children of v are 2v and 2v + 1; allocate 4n slots
- Build O(n), point update O(log n), range query O(log n)
- Query cases: no overlap returns the identity, full overlap returns t[v], partial recurses
- Identities: sum 0, product 1, min +inf, max -inf, gcd 0, xor 0
- Lazy range add on sums: sum += d * length, lazy += d; push before visiting children
- Static range min with no updates: sparse table, O(n log n) build and O(1) query
- Iterative bottom-up tree uses 2n slots and is much faster in Python than recursion
Common mistakes
- Allocating only 2n for a recursive segment tree, causing index errors.
- Using a segment tree when a prefix sum or Fenwick tree is enough.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Draw the max segment tree for [4, 9, 2, 7] and show which nodes answer max over [1, 3].
- Exercise 2medium
Add a method update(i, x) to the MinTree example that sets a[i] = x in O(log n).
- Exercise 3hard
Design the node and combine function for a segment tree that answers the maximum subarray sum inside any [l, r], with point updates.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between a segment tree and a Fenwick tree?
- Both give O(log n) updates and queries. A Fenwick tree is smaller and simpler but mainly handles sums; a segment tree handles any associative operation and range updates with lazy propagation.
- How much memory does a segment tree use?
- A recursive array-based tree uses up to 4n slots. An iterative bottom-up tree uses exactly 2n.
- What does lazy propagation actually do?
- It records a pending update on a node that is fully covered, instead of updating every element below it. The update is passed down to the children only when a later operation needs to look inside that node.
- Are segment trees asked in coding interviews?
- They are uncommon in typical company interviews, which favour prefix sums, heaps and Fenwick-style ideas, but they are standard in competitive programming. Knowing how to build and query one is enough for most interviews.