Short answer: A segment tree partitions an array into segments of length a power of two, stored in a heap-indexed array of about 2n cells. A range query visits O(log n) disjoint nodes whose segments cover the query exactly. A point update walks one root path. A range update that would otherwise touch every leaf stores a lazy tag on a node and pushes the tag down when a later query needs the children. Both the query and the lazy update are O(log n).
What the problem actually asks
A Fenwick tree is ideal for prefix sums and awkward for a range minimum, a range assignment, or a query that is not invertible. A segment tree stores the answer for every dyadic segment explicitly. Any query interval is a union of O(log n) of those segments, the same decomposition a binary carry produces.
A range update that rewrote every covered leaf would be linear. The lazy tag says the node already knows the update and the children do not yet. Pushing the tag is deferred until a walk actually enters the node.
What the algorithm guarantees
Build is O(n). Point update, range query, and lazy range update are O(log n) for an associative combine such as sum, minimum, or maximum. Extra memory is about 2n cells, or 4n in the common recursive layout that allocates a full power of two. The combine must be associative. Subtraction as a combine is not a segment-tree operation. The inverse, if one exists, is how a Fenwick tree avoids storing both children.
Lazy propagation is correct only if tags compose. A range-add tag composes by addition. A range-assign tag overwrites a pending add. The push function has to implement that algebra, and a query must push before it reads a child. Forgetting the push returns a stale child next to a correct parent.
The working steps
- Place the leaves in index order at the bottom of a 1-based heap array, and set each internal node to the combine of its two children. The parent of i is floor(i/2).
- A query on [l, r] walks from the root. A node segment disjoint from [l, r] contributes nothing. A node segment contained in [l, r] contributes its stored value. A partial overlap recurses into both children.
- A point update changes a leaf and recomputes ancestors up to the root.
- A range update on a node that is fully covered composes a lazy tag and updates that node’s stored value. It does not enter the children.
- Before a walk reads a child, push the parent’s tag into the children and clear the parent tag.
The logarithmic bound is for dyadic ranges on an array, with an associative combine. It is not a Fenwick tree, and it is not a sparse table. A sparse table answers a static idempotent query in constant time and cannot update. A segment tree updates. Persistent and dynamic versions exist and add a logarithm or a memory factor. They are not required for the array case.
Approaches that look simpler and fail
| Approach | Why it fails when a lazy tag is never pushed |
|---|---|
| Store the tag and query a child without pushing | The child still holds the pre-update value. The parent was updated in place, so the two disagree. |
| Combine overlapping node values | The O(log n) cover is a partition of the query. Adding a parent and its child double-counts the child’s segment. |
| Use a non-associative combine | The value stored at a node depends on having been built from its children in a way that matches any later split of the query. Non-associative operations break that match. |
| Allocate exactly n cells for an internal-node tree | The leaves and the internal nodes both need slots. The usual safe allocation is 4n, or 2n for a careful bottom-up layout. |
Prefix sums with point updates and less memory belong to a Fenwick tree. Static range minimum belongs to a sparse table. The segment tree is the structure that does both updates and arbitrary associative range queries, including lazy range updates.
A working example
This Python fragment is a segment tree for range sums. A point update and a query over a disjoint cover both take a walk of length O(log n). It prints 10, the sum of indexes 1 through 3 after the update.
class Seg:
def __init__(self, a):
self.n = len(a)
self.t = [0] * (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] = self.t[2 * v] + self.t[2 * v + 1]
def add(self, i, delta, v=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if lo == hi:
self.t[v] += delta
return
mid = (lo + hi) // 2
if i <= mid:
self.add(i, delta, 2 * v, lo, mid)
else:
self.add(i, delta, 2 * v + 1, mid + 1, hi)
self.t[v] = self.t[2 * v] + self.t[2 * v + 1]
def query(self, L, R, v=1, lo=0, hi=None):
if hi is None:
hi = self.n - 1
if R < lo or hi < L:
return 0
if L <= lo and hi <= R:
return self.t[v]
mid = (lo + hi) // 2
return self.query(L, R, 2 * v, lo, mid) + self.query(L, R, 2 * v + 1, mid + 1, hi)
a = [1, 2, 3, 4]
seg = Seg(a)
seg.add(2, 1) # 3 becomes 4
assert seg.query(1, 3) == 2 + 4 + 4
print(seg.query(1, 3))
Where it is used
A segment tree answers a range sum or a range minimum while single positions change, which is the live histogram and the coverage counter. Computational-geometry libraries use the same tree for stabbing queries. A sparse table is the static special case that does not support updates.
When you can drop this algorithm
Drop a segment tree for static prefix sums. An array of prefixes is enough. Drop it for a static idempotent range query if constant time matters. Use a sparse table. Keep the segment tree when the array changes and the query is a range combine.
Why this stays published
We publish this so a search for a segment tree returns the O(log n) disjoint cover and the lazy tag that must be pushed before a child is read. A segment tree answers an associative range query and a point or lazy range update in O(log n) time by storing the answer on every dyadic segment.
本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。
