Segment Trees (DSA #15)
Prefix sums answer any range-sum query in \(O(1)\) — until an element changes. Then you rebuild the prefix array in \(O(n)\), and a workload with many updates becomes quadratic. A segment tree resolves the tension: it answers range queries and point updates both in \(O(\log n)\), by storing precomputed aggregates over a hierarchy of ranges. It is the general-purpose structure for “range aggregate with updates”, and it generalizes from sums to min, max, gcd, and custom merge functions.
This chapter builds a segment tree, covers point update and range query, and introduces lazy propagation for range updates.
The tension prefix sums leave
Given an array, prefix sums give:
- range sum query: \(O(1)\),
- point update: \(O(n)\) (every later prefix shifts).
A segment tree rebalances the cost: both become \(O(\log n)\). When a problem mixes range queries with updates, that is the right trade.
The structure
A segment tree is a binary tree where each node represents an interval [l, r] of the array:
- The root covers
[0, n-1]. - Each internal node splits into
[l, mid](left) and[mid+1, r](right). - Each leaf covers a single element.
Each node stores the aggregate (here, the sum) of its interval. A query decomposes an arbitrary range into \(O(\log n)\) canonical nodes whose aggregates combine into the answer.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum width=1.35cm, minimum height=0.62cm, font=\small\bfseries},
a/.style={->, thick}]
\node[n, fill=orange!20] (r) at (0,0) {[0,7] 36};
\node[n, fill=blue!12] (l) at (-2.5,-1.1) {[0,3] 10};
\node[n, fill=blue!12] (rr) at (2.5,-1.1) {[4,7] 26};
\node[n, fill=green!16] (ll) at (-3.7,-2.2) {[0,1] 3};
\node[n, fill=green!16] (lr) at (-1.3,-2.2) {[2,3] 7};
\node[n, fill=green!16] (rl) at (1.3,-2.2) {[4,5] 11};
\node[n, fill=green!16] (rrr) at (3.7,-2.2) {[6,7] 15};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
\draw[a] (rr) -- (rl); \draw[a] (rr) -- (rrr);
\node[font=\scriptsize, anchor=north] at (-4.2,-2.7) {...leaves hold single elements};
\end{tikzpicture}
Build in O(n)
Because the tree is a full binary tree over \(n\) leaves, it fits in an array of size \(4n\). Build bottom-up by recursion:
class SegTree:
def __init__(self, nums):
self.n = len(nums)
self.tree = [0] * (4 * self.n) # safe upper bound
self._build(1, 0, self.n - 1, nums)
def _build(self, node, l, r, nums):
if l == r:
self.tree[node] = nums[l]
return
mid = (l + r) // 2
self._build(2*node, l, mid, nums)
self._build(2*node + 1, mid + 1, r, nums)
self.tree[node] = self.tree[2*node] + self.tree[2*node + 1]
The build visits each node once: \(O(n)\) time, \(O(4n)\) space.
Point update
Updating one element means updating its leaf and every ancestor. Walk down to the leaf, change it, and recompute on the way back up.
def update(self, node, l, r, idx, val):
if l == r:
self.tree[node] = val
return
mid = (l + r) // 2
if idx <= mid:
self.update(2*node, l, mid, idx, val)
else:
self.update(2*node + 1, mid + 1, r, idx, val)
self.tree[node] = self.tree[2*node] + self.tree[2*node + 1]
Exactly one leaf is reached, so the work is the tree height: \(O(\log n)\).
Range query
The heart of the structure. Given a range [ql, qr], there are three cases at each node:
- No overlap — return the identity (0 for sum).
- Total overlap — return the node’s stored aggregate immediately.
- Partial overlap — recurse into both children and combine.
def query(self, node, l, r, ql, qr):
if qr < l or r < ql: # no overlap
return 0
if ql <= l and r <= qr: # total overlap
return self.tree[node]
mid = (l + r) // 2 # partial overlap
left = self.query(2*node, l, mid, ql, qr)
right = self.query(2*node + 1, mid + 1, r, ql, qr)
return left + right
Any range splits into \(O(\log n)\) fully-covered nodes, so the query is \(O(\log n)\).
\begin{tikzpicture}[font=\rmfamily, >=stealth,
n/.style={draw, thick, rounded corners=2pt, minimum width=1.35cm, minimum height=0.62cm, font=\small\bfseries},
hit/.style={n, fill=orange!30, very thick},
a/.style={->, thick}]
\node[n] (r) at (0,0) {[0,7]};
\node[n] (l) at (-2.5,-1.1) {[0,3]};
\node[hit] (rr) at (2.5,-1.1) {[4,7]};
\node[hit] (ll) at (-3.7,-2.2) {[0,1]};
\node[n] (lr) at (-1.3,-2.2) {[2,3]};
\node[hit] (rl) at (1.3,-2.2) {[4,5]};
\node[n] (rrr) at (3.7,-2.2) {[6,7]};
\draw[a] (r) -- (l); \draw[a] (r) -- (rr);
\draw[a] (l) -- (ll); \draw[a] (l) -- (lr);
\draw[a] (rr) -- (rl); \draw[a] (rr) -- (rrr);
\node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.7) {query [1,4]: cover with nodes [0,1] and [4,5] (and part of [2,3])};
\end{tikzpicture}
Range update: lazy propagation
If an update covers a whole range, recursively updating every leaf is \(O(n)\). Lazy propagation defers the work: store a lazy value at a node meaning “this whole interval needs this update but the children have not been told yet”, and push it down only when you actually visit the children.
def range_add(self, node, l, r, ql, qr, val):
self._push(node, l, r) # flush pending lazy first
if qr < l or r < ql:
return
if ql <= l and r <= qr:
self.tree[node] += val * (r - l + 1)
self.lazy[node] += val # defer to children
return
mid = (l + r) // 2
self.range_add(2*node, l, mid, ql, qr, val)
self.range_add(2*node + 1, mid + 1, r, ql, qr, val)
self.tree[node] = self.tree[2*node] + self.tree[2*node + 1]
def _push(self, node, l, r):
if self.lazy[node] and l != r:
mid = (l + r) // 2
self.lazy[2*node] += self.lazy[node]
self.lazy[2*node + 1] += self.lazy[node]
self.tree[2*node] += self.lazy[node] * (mid - l + 1)
self.tree[2*node + 1] += self.lazy[node] * (r - mid)
self.lazy[node] = 0
Lazy propagation turns range update from \(O(n)\) into \(O(\log n)\) by never touching unaffected subtrees.
Where segment trees are used
- Range sum/min/max with point or range updates.
- Counting inversions, number of elements greater than k in a range (merge-sort tree variants).
- Interval scheduling and skyline problems.
- Competitive programming staples: range add + range max, range assign + range sum.
If the operation is only prefix-sum with point updates, a Fenwick tree (Chapter 16) is simpler and smaller. Segment trees are the general tool when you need arbitrary range aggregates and updates.
Pitfalls
- Wrong array size. \(4n\) is the safe bound for the recursive layout; \(2n\) can overflow for unbalanced splits.
- Forgetting the identity element. The no-overlap return must be the identity for the operation (0 for sum, \(+\infty\) for min) — get this wrong and queries fail.
- Mixing inclusive and exclusive ranges. Decide once (
[l, r]inclusive) and be consistent in every method. - Mutating without recomputing ancestors. An update must propagate the change up; a leaf-only write leaves stale aggregates.
- Forgetting
_pushbefore descending with lazy. Skipping it corrupts children with stale values. - Using a segment tree when a prefix sum suffices. If there are no updates, prefix sums are \(O(1)\) per query and simpler.
Why is a segment tree preferable to prefix sums when updates exist? What does lazy propagation defer, and why is it correct?
ASolution
Prefix sums give \(O(1)\) queries but \(O(n)\) updates; a segment tree gives \(O(\log n)\) for both. Lazy propagation stores a pending update on a fully-covered node and applies it to children only when they are next visited, which is correct because the node’s aggregate is updated immediately and the deferred value is exactly the work owed to its descendants.
Next: Fenwick Trees (DSA #16) — the compact structure for prefix sums with updates.