Segment tree

On this page 7

A segment tree is a binary tree built over the index range of an array in which every node stores an aggregate, such as a sum, minimum or maximum, of one contiguous interval. Among data structures in programming, it is the standard tool for answering range queries in O(log n) time while still allowing elements to change, which a plain prefix-sum array cannot do efficiently.

The structure trades memory for speed: it uses about 2n to 4n nodes for an array of n elements, but both a query over any interval and a point update touch only a logarithmic number of nodes. Competitive programmers, database engines and computational geometry libraries rely on it whenever data is both queried by range and modified frequently.

How a segment tree divides an array

A segment tree works by recursively halving the index interval until each leaf covers a single element. The root covers the whole range [0, n-1], its left child covers the first half and its right child covers the second half, and so on. Each internal node stores the result of an associative combine operation applied to its two children, so the root holds the aggregate of the entire array.

Construction runs bottom-up in O(n) time because every node is computed exactly once from its children. Implementations usually store the tree in a flat array: the root sits at index 1, and the children of node i sit at 2i and 2i + 1. This implicit layout avoids pointers and keeps memory access predictable, which matters for cache performance.

The following table shows the core operations and their costs for an array of n elements.

OperationTime complexityWhat it touches
BuildO(n)Every node once
Range queryO(log n)At most about 4 nodes per tree level
Point updateO(log n)One leaf and all its ancestors
Range update with lazy propagationO(log n)Covering nodes plus deferred tags
MemoryO(n)Up to 4n slots in the array layout
Operation costs of a standard segment tree

Range queries and lazy propagation

A range query decomposes the requested interval into a small set of disjoint canonical nodes whose intervals exactly cover it. The search descends from the root: a node fully inside the query contributes its stored value, a node fully outside is ignored, and a partially overlapping node passes the query to its children. At most O(log n) canonical nodes are combined, which yields the logarithmic bound.

Updating a whole range element by element would cost O(n log n). Lazy propagation solves this by storing a pending update, often called a tag, on the highest nodes that fully cover the range. The tag is pushed down to the children only when a later operation needs them, so a range assignment or range addition also runs in O(log n).

Lazy propagation requires that pending updates can be composed with each other and applied to an aggregate without visiting individual elements. Adding a constant to a range sum works because the new sum equals the old sum plus the constant times the interval length. The table lists common combinations.

AggregateRange updateHow the tag adjusts a node
SumAdd a constant cSum increases by c times length
SumAssign a value vSum becomes v times length
Minimum or maximumAdd a constant cExtreme value shifts by c
Minimum or maximumAssign a value vExtreme value becomes v
Count of set bitsFlip all bitsCount becomes length minus count
Common aggregate and update pairs

Variants of the segment tree

Several variants extend the basic structure for specific workloads and constraints. The iterative bottom-up segment tree stores leaves at positions n to 2n – 1 and walks upward with simple loops, which halves memory and runs faster in practice. A persistent segment tree copies only the O(log n) nodes on each update path, so every earlier version of the array remains queryable.

A dynamic or sparse segment tree creates nodes only when they are first touched, which allows index ranges of 10^9 or more without allocating the full structure. A merge sort tree stores a sorted list in each node to answer order-statistic questions, and a two-dimensional segment tree nests one tree inside another for rectangle queries on a grid.

  • Segment tree beats handle operations such as range minimum assignment with amortized guarantees.
  • Li Chao trees store linear functions and answer the minimum value at a point, which appears in convex hull optimization.
  • Kinetic segment trees track values that change linearly over time.

The segment tree is more general but heavier than its closest alternatives. A Fenwick tree, also called a binary indexed tree, answers prefix sums and point updates with less code and about n memory slots, but it handles only invertible operations easily and cannot answer range minimum without extra tricks. A sparse table answers idempotent queries such as range minimum in O(1), yet it supports no updates at all.

The comparison below helps decide which structure fits a problem.

StructureQuery costUpdate costBest fit
Prefix-sum arrayO(1)O(n)Static data, sums only
Sparse tableO(1) for idempotent operationsNot supportedStatic range minimum or maximum
Fenwick treeO(log n)O(log n)Prefix sums with point updates
Segment treeO(log n)O(log n), ranges with lazy tagsAny associative operation, range updates
Square root decompositionO(sqrt n)O(1) to O(sqrt n)Unusual operations, simpler code
Range query structures side by side

Unlike a binary search tree or an AVL tree, a segment tree indexes positions rather than keys. Its shape is fixed by n and never needs rebalancing, which makes worst-case behavior predictable.

Implementation pitfalls and limitations

Most segment tree bugs come from boundary handling and lazy tags. Off-by-one errors appear when code mixes inclusive and half-open intervals, and a recursive tree sized at exactly 2n overflows when n is not a power of two. The safe rule is to allocate 4n slots for the recursive layout or use the iterative 2n layout consistently.

SymptomLikely causeFix
Wrong results after range updatesTag not pushed before descendingPush down at the start of every recursive call
Index out of boundsArray sized 2n for recursive layoutAllocate 4n or switch to iterative form
Incorrect minimum after updateWrong identity elementUse positive infinity for minimum
Assignment and addition conflictTags composed in wrong orderLet assignment clear pending additions
Stack overflow on large inputsDeep recursion in some runtimesUse the iterative bottom-up version
Frequent mistakes and their fixes

The combine operation must be associative, and it needs an identity element for empty intervals: zero for sum, positive infinity for minimum, negative infinity for maximum. Non-associative operations such as arithmetic mean must be expressed through associative parts, for example by storing sum and count together. For purely static data, a simpler structure is usually faster.

A non-technical view

Imagine a long row of shop receipts and a manager who keeps asking for the total of any stretch, such as receipts 120 to 480. Adding them one by one each time is slow. A segment tree prepares subtotals for blocks of receipts in advance: halves, quarters, eighths and so on.

Any stretch can then be answered by adding just a handful of ready-made subtotals. When one receipt changes, only the few subtotals that include it need correcting. The structure trades extra storage for very fast answers, even when the data keeps changing.

A concrete example

A monitoring service records the response latency of a web application every second, which produces 86,400 readings per day. Engineers want the worst latency in any time window they select on a dashboard, and late-arriving measurements regularly correct earlier readings.

A segment tree storing the maximum of each interval answers every window query by combining at most a few dozen nodes, since the tree over 86,400 leaves has only 17 levels. A corrected reading updates one leaf and its 17 ancestors. Compared with scanning the raw readings, which could take tens of thousands of comparisons per query, the dashboard responds in microseconds regardless of window size, and corrections never require rebuilding the structure.