A segment tree is a binary tree over an array in which every node stores a summary (sum, minimum, maximum, GCD, …) of one contiguous segment. The root covers the whole array, each child covers half of its parent's segment, and the leaves are single elements. Any range query is answered by combining O(log n) precomputed segments, and a point update only touches the O(log n) nodes above one leaf. With lazy propagation, even "add 5 to every element in [l, r]" runs in O(log n).
Think of it like
A sales report rolled up by region
A national retailer knows each store's sales, each district's total, each region's total and the national total. To answer "total for stores 120 to 480", the analyst adds a handful of district and region totals instead of 361 store numbers. When one store revises its figure, only its district, its region and the national total change. A segment tree is that report, with every level splitting its parent exactly in half.
The problem it solves
You have an array that changes over time, and you must repeatedly answer questions about ranges: the sum of a[l..r], its minimum, its maximum. The two obvious approaches each make one operation slow.
| Approach | Range query | Point update | Range update |
|---|---|---|---|
| Plain array | O(n) | O(1) | O(n) |
| Prefix-sum array (see Prefix Sums & Difference Arrays) | O(1) | O(n) | O(n) |
| Segment tree | O(log n) | O(log n) | O(n) without lazy tags |
| Segment tree with lazy propagation | O(log n) | O(log n) | O(log n) |
Structure
Node i covers a segment [l, r]. If l == r it is a leaf holding a[l]; otherwise it splits at m = ⌊(l + r) / 2⌋ into a left child for [l, m] and a right child for [m + 1, r], and stores the combination of its two children. Like a heap, the tree is stored in an array: with 1-based indexing the children of node i are 2i and 2i + 1.
[0,7] 28
/ \
[0,3] 11 [4,7] 17
/ \ / \
[0,1] 3 [2,3] 8 [4,5] 10 [6,7] 7
/ \ / \ / \ / \
2 1 5 3 4 6 0 7Build in O(n)
Build recursively: fill the leaves from the array, then set each internal node to the combination of its children on the way back up (a post-order pass). There are 2n − 1 nodes and each does O(1) work, so building is O(n).
Range query
To answer sum(ql, qr), start at the root and compare the node's segment [l, r] with the query range. There are only three possibilities:
- 1
No overlap
qr < lorr < ql: return the identity (0 for sums, +∞ for minimum). - 2
Full overlap
ql <= landr <= qr: return the stored value without descending. - 3
Partial overlap
Recurse into both children and combine their answers.
| Node | Segment | Overlap with [2, 6] | Contributes |
|---|---|---|---|
| Root | [0, 7] | Partial | Recurse |
| Left child | [0, 3] | Partial | Recurse |
| [0, 1] | None | 0 | |
| [2, 3] | Full | 8 | |
| Right child | [4, 7] | Partial | Recurse |
| [4, 5] | Full | 10 | |
| [6, 7] | Partial | Recurse: leaf 6 gives 0, leaf 7 gives 0 (no overlap) |
Point update
To set a[pos] = v, walk from the root to the leaf for pos (choosing left or right by comparing with m), overwrite the leaf, and recompute each ancestor from its children on the way back up. Exactly one node per level changes: O(log n). Setting a[3] = 9 in the example changes the leaf [3,3] and then [2,3], [0,3] and [0,7].
Lazy propagation for range updates
"Add v to every element of [l, r]" would need up to n point updates. Lazy propagation borrows the trick from the query: when an update fully covers a node, fix that node's summary immediately and leave a note (a lazy tag) saying "my children still owe +v". The children are only brought up to date when some later operation needs to look inside.
- 1
Fully covered
Apply the update to the node:
sum += v × (r − l + 1)andlazy += v. Stop; do not descend. - 2
Partially covered
Push first: apply the node's pending tag to both children and clear it. Then recurse into the children and recompute the node from them.
- 3
Queries push too
A query that must descend into a node with a pending tag pushes it first, so the children it reads are correct.
- 4
Cost
Updates and queries touch the same O(log n) nodes as a query does, each doing O(1) extra work.
a = [2, 1, 5, 3, 4, 6, 0, 7]: range_add(1, 4, 10) stops at fully covered nodes and leaves violet tags, then query(3, 5) pushes a tag down before reading inside it (answer 33) and query(0, 7) returns the root's sum, 68.Iterative bottom-up segment tree
For point updates and range queries there is a compact non-recursive version. Store the leaves at t[n .. 2n − 1] and each internal node at t[i] = t[2i] ⊕ t[2i + 1] for i from n − 1 down to 1. An update writes the leaf and climbs with i = i / 2. A query over the half-open range [l, r) moves both ends upward, taking a node whenever it sticks out of its parent's coverage.
Recursive (top-down)
- 4n memory
- Supports lazy propagation and any custom combine
- Easy to adapt: binary search on the tree, merge-sort trees
Iterative (bottom-up)
- Exactly 2n memory, works for any n
- No recursion, typically 2 to 3 times faster
- Simple for commutative operations; lazy versions get intricate
Variants
Any associative operation with an identity element works: change the combine function and the value returned for "no overlap".
| Variant | Node stores | Identity / notes |
|---|---|---|
| Range minimum / maximum | min or max of the segment | +∞ / −∞ |
| Range GCD | gcd of the segment | 0, since gcd(0, x) = x |
| Count of elements satisfying a predicate | a count | 0 |
| Maximum subarray sum | best, prefix best, suffix best, total | Four values merged per node |
| Merge sort tree | the sorted list of its segment | Answers "how many values below k in [l, r]" in O(log² n) |
| Dynamic (sparse) tree | nodes created on demand | Handles coordinate ranges like 10⁹ without allocating them |
| Persistent tree | new nodes on each update, old versions kept | Queries on any past version; k-th smallest in a range |
Segment tree vs Fenwick tree
| Aspect | Segment tree | Fenwick tree |
|---|---|---|
| Memory | 2n to 4n | n + 1 |
| Code size | 30 to 60 lines | About 10 lines |
| Operations | Any associative operation | Invertible ones such as sum and XOR (prefix differences) |
| Range minimum with updates | Yes | Not in general |
| Range update + range query | Lazy propagation | Possible with two trees, sums only |
| Constant factor | Larger | Very small |
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Build | O(n) | O(n) | 2n − 1 nodes; allocate 4n for the recursive layout |
| Range query | O(log n) | O(log n) | At most 4 nodes per level; recursion depth log n |
| Point update | O(log n) | O(log n) | One node per level changes |
| Range update (lazy) | O(log n) | O(log n) | Tags postpone work on fully covered nodes |
| Iterative query / update | O(log n) | O(1) | 2n array, no recursion |
| q mixed operations | O((n + q) log n) | O(n) | Versus O(n · q) naively |
Implementation
1-based node indices with children 2i and 2i + 1. Queries use inclusive bounds and return the identity (0) for segments outside the range.
class SegmentTree:
"""Range-sum queries and point assignments in O(log n)."""
def __init__(self, a: list[int]):
self.n = len(a)
self.t = [0] * (4 * self.n) # node i has children 2i and 2i + 1
if self.n:
self._build(a, 1, 0, self.n - 1)
def _build(self, a, i, l, r):
if l == r:
self.t[i] = a[l]
return
m = (l + r) // 2
self._build(a, 2 * i, l, m)
self._build(a, 2 * i + 1, m + 1, r)
self.t[i] = self.t[2 * i] + self.t[2 * i + 1]
def query(self, ql: int, qr: int) -> int:
"""Sum of a[ql..qr], inclusive."""
return self._query(1, 0, self.n - 1, ql, qr)
def _query(self, i, l, r, ql, qr):
if qr < l or r < ql:
return 0 # no overlap: identity
if ql <= l and r <= qr:
return self.t[i] # full overlap: stored answer
m = (l + r) // 2 # partial overlap: ask both halves
return (self._query(2 * i, l, m, ql, qr) +
self._query(2 * i + 1, m + 1, r, ql, qr))
def update(self, pos: int, value: int) -> None:
"""Set a[pos] = value."""
self._update(1, 0, self.n - 1, pos, value)
def _update(self, i, l, r, pos, value):
if l == r:
self.t[i] = value
return
m = (l + r) // 2
if pos <= m:
self._update(2 * i, l, m, pos, value)
else:
self._update(2 * i + 1, m + 1, r, pos, value)
self.t[i] = self.t[2 * i] + self.t[2 * i + 1] # recompute on the way up
st = SegmentTree([2, 1, 5, 3, 4, 6, 0, 7])
print(st.query(2, 6)) # 18
st.update(3, 9)
print(st.query(2, 6)) # 24Key takeaways
- Each node summarizes a contiguous segment; children split it in half, so the tree has height ⌈log₂ n⌉ and 2n − 1 nodes.
- A range query combines at most about 4 log₂ n stored segments: skip disjoint nodes, take covered nodes whole, recurse only on partial overlaps.
- A point update rewrites one leaf and the log n ancestors above it.
- Lazy propagation makes range updates O(log n) by tagging fully covered nodes and pushing tags down only when needed.
- Any associative operation with an identity works (sum, min, max, GCD, custom merges); prefer a Fenwick tree when plain sums suffice.
Common pitfalls
- Allocating only 2n slots for the recursive layout, which overflows when n is not a power of two. Use 4n (or the iterative 2n layout).
- Returning the wrong identity for disjoint segments, such as 0 for a minimum query.
- Forgetting to push lazy tags before recursing, or forgetting to multiply the added value by the segment length for sums.
- Mixing inclusive and half-open ranges between the recursive and iterative versions.
- Using 32-bit integers for sums that can reach n × max value (10⁵ × 10⁹ overflows).
Interview tips
- Start with the trade-off table: prefix sums are O(1) query but O(n) update; a segment tree balances both at O(log n).
- Explain the three overlap cases and the "at most two partial nodes per level" argument for O(log n).
- Mention lazy propagation as soon as the problem has range updates, and say what the tag means for your operation.
- Many interview problems that seem to need a segment tree can use a Fenwick tree, coordinate compression or a sweep line; mention the simpler option if it applies.
Real-world applications
- Competitive programming staple for range queries with updates.
- Computational geometry sweep lines: rectangle union area, skyline, interval stabbing.
- Database and analytics engines answering range aggregates over changing data.
- Game and graphics engines tracking ranges of dirty or occupied cells.
- Order statistics such as counting smaller elements after coordinate compression.
Practice problems
Test yourself
How many array slots should you allocate for a recursive segment tree over n elements to be safe?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.