← The Ledger
Vol. I, No. 27 · Range Structures

The Segment Tree

Precomputed answers for every power-of-two interval, so that any range is a handful of reads.

Written by Khushal Agrawal

loading…

Range Queries Over An Array

An array of n numbers must answer "what is the sum (or minimum, or maximum) of elements l through r" while individual elements keep changing. The two obvious representations each make one operation linear.

                 update      range query
plain array      O(1)        O(n)
prefix sums      O(n)        O(1)
segment tree     O(log n)    O(log n)

A plain array answers a query by reading every element in the range. A prefix-sum array answers in two reads, but a single update shifts every later prefix. A segment tree stores the answer for a set of precomputed intervals, so that any range is a union of O(log n) of them and any element belongs to O(log n) of them.

The Tree Of Intervals

The root covers the whole array [0, n). Each internal node covering [lo, hi) has two children covering [lo, mid) and [mid, hi), and each leaf covers one element. Every node stores the aggregate of its interval.

For the array 5 3 7 1 4 6 2 8, the leaves hold the elements, the next level holds the pair sums 8 8 10 10, then 16 20, and the root holds 36. The tree is complete and has height ⌈log₂ n⌉. Bentley's 1977 segment tree, built for rectangle problems in computational geometry, stores interval lists rather than aggregates; the name is shared, the purpose is not.

Array Layout

Like a binary heap, the complete tree lives in a flat array with no pointers. In the bottom-up layout the leaves occupy t[n .. 2n) and node i has children 2i and 2i + 1.

void build(long *t, const long *a, int n) {
    for (int i = 0; i < n; i++) t[n + i] = a[i];
    for (int i = n - 1; i > 0; i--)
        t[i] = t[2*i] + t[2*i + 1];      // t[1] is the root
}

The array has 2n slots and building it is O(n). The recursive top-down layout used by most textbooks allocates 4n to be safe for any n; the bottom-up layout needs only 2n and works for any n when the operation is commutative.

Point Update

Changing one element changes exactly the aggregates of the intervals containing it: one leaf and its ancestors. The update writes the leaf, then walks to the root recomputing each parent from its two children.

void update(long *t, int n, int i, long v) {
    for (t[i += n] = v; i > 1; i >>= 1)
        t[i >> 1] = t[i] + t[i ^ 1];     // parent = this node + its sibling
}

i ^ 1 flips the last bit to reach the sibling, and i >> 1 is the parent. The walk touches ⌈log₂ n⌉ parents, so the update is O(log n) worst-case, against O(n) for rebuilding a prefix-sum array.

Range Query

A query on [l, r) starts with two pointers at the leaf level and moves them up together. Whenever a boundary node is a child whose parent would cover elements outside the range, that node is taken whole and the pointer steps inward.

long query(const long *t, int n, int l, int r) {   // [l, r)
    long res = 0;
    for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
        if (l & 1) res += t[l++];   // l is a right child: take it
        if (r & 1) res += t[--r];   // the node left of r is a left child: take it
    }
    return res;
}

On 5 3 7 1 4 6 2 8, the query [1, 7) takes the leaf 3, the node [2, 4) holding 8, the node [4, 6) holding 10, and the leaf 2: four reads, total 23.

Why O(log n) Nodes

The nodes a query takes form the canonical decomposition of the range: the fewest tree intervals whose union is exactly [l, r). At each level the loop takes at most one node at the left boundary and one at the right.

n = 16, query [2, 13)
leaves     take [12, 13)
level 1    take [2, 4)
level 2    take [4, 8)  and  [8, 12)
4 nodes instead of 11 elements; at most 2 per level

With ⌈log₂ n⌉ levels, a query reads at most 2 log₂ n nodes. A node is taken only when its parent sticks out of the range; if the parent fits inside, the loop takes the parent at the next level instead.

Any Associative Operation

Nothing in the update or query depends on addition. Any associative operation with an identity element works: minimum with +∞, maximum, gcd with 0, bitwise or, or 2×2 matrix products for linear recurrences. The same tree over 5 3 7 1 4 6 2 8 with min holds 1 at the root.

// non-commutative ops (matrix product, string concat): keep both sides
T left = ID, right = ID;
for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
    if (l & 1) left  = op(left, t[l++]);
    if (r & 1) right = op(t[--r], right);
}
return op(left, right);

When the operation is not commutative, the left and right pieces are accumulated separately and combined in order; with n a power of two the layout keeps intervals contiguous.

Lazy Propagation

Adding v to every element of a range would touch up to n leaves. Lazy propagation stops at the canonical nodes instead: it fixes their aggregates directly and records a pending tag meaning "this still applies to my children".

void add(int x, int lo, int hi, int l, int r, long v) {
    if (r <= lo || hi <= l) return;            // disjoint
    if (l <= lo && hi <= r) {                  // fully covered
        sum[x] += v * (hi - lo);                 // fix this node now
        tag[x] += v;                             // defer the children
        return;
    }
    push(x, lo, hi);
    int mid = (lo + hi) / 2;
    add(2*x, lo, mid, l, r, v);
    add(2*x + 1, mid, hi, l, r, v);
    sum[x] = sum[2*x] + sum[2*x + 1];
}

A range update visits the same O(log n) nodes a query would, plus the ancestors it must recompute, so range update and range query are both O(log n) worst-case. Adding 2 to [0, 4) of the example array changes only the node for [0, 4), from 16 to 24, and the root; the four leaves stay stale until something reads them.

Pushing Tags Down

A tag must reach the children before anything reads or writes beneath its node. push applies the parent's pending tag to both children, adjusting their aggregates by the tag times their lengths, and clears it.

void push(int x, int lo, int hi) {
    if (!tag[x]) return;
    int mid = (lo + hi) / 2;
    sum[2*x]     += tag[x] * (mid - lo);  tag[2*x]     += tag[x];
    sum[2*x + 1] += tag[x] * (hi - mid);  tag[2*x + 1] += tag[x];
    tag[x] = 0;
}

Tags must compose. Two pending adds merge into one add; an "assign c" followed by "add v" merges into "assign c + v". Any update family closed under composition, such as affine maps x → ax + b, can be made lazy this way.

Descending For A Prefix

Some queries are answered by one walk from the root instead of a range decomposition. Finding the smallest index whose prefix sum reaches k, with non-negative elements, compares k against each left child's total.

int find_prefix(const long *t, int n, long k) {   // n a power of two
    int x = 1;
    while (x < n) {
        if (t[2*x] >= k) x = 2*x;               // answer is in the left half
        else { k -= t[2*x]; x = 2*x + 1; }      // skip the left half's total
    }
    return x - n;
}

On 5 3 7 1 4 6 2 8 with k = 20, the left half sums to 16, so the walk goes right with k = 4 and ends at index 4. This is O(log n), where binary search over separate range queries costs O(log² n).

Fenwick Trees

When the operation has an inverse, as addition does, a Fenwick tree or binary indexed tree does the same job in n slots. Entry bit[i] stores the sum of the i & -i elements ending at i.

void add(long *bit, int n, int i, long v) {      // 1-indexed
    for (; i <= n; i += i & -i) bit[i] += v;
}
long prefix(const long *bit, int i) {            // a[1] + ... + a[i]
    long s = 0;
    for (; i > 0; i -= i & -i) s += bit[i];
    return s;
}

A range sum is prefix(r) − prefix(l − 1). Each loop runs at most log₂ n times by stripping or adding the lowest set bit. Minimum has no inverse, so Fenwick's subtraction trick does not apply and a segment tree is needed.

Persistent Segment Trees

A point update changes one root-to-leaf path. Copying that path instead of overwriting it leaves the old root valid, so every version stays queryable at O(log n) extra nodes per update.

int update(int x, int lo, int hi, int i, long v) {   // returns a new root
    int y = clone(x);                                 // one new node per level
    if (hi - lo == 1) { sum[y] = v; return y; }
    int mid = (lo + hi) / 2;
    if (i < mid) L[y] = update(L[x], lo, mid, i, v);
    else         R[y] = update(R[x], mid, hi, i, v);
    sum[y] = sum[L[y]] + sum[R[y]];
    return y;
}

This is the path copying of persistent structures. Building one version per prefix of an array, over value counts, answers "k-th smallest in a subarray" by descending two versions at once. Each version costs ⌈log₂ n⌉ + 1 new nodes, so n versions fit in O(n log n) memory rather than O(n²) for full copies.

Engineering Trade-offs

A segment tree gives O(log n) worst-case point update, range query, and lazy range update, for any associative operation, in an array of 2n to 4n slots with no pointers. It also supports descent queries and persistence with the same node layout.

The costs are memory and constants. It uses two to four times the space of the data, against n slots for a Fenwick tree, and its code is longer and easier to get wrong, especially lazy tag composition. It assumes a fixed index range; a dynamic key set needs an augmented balanced tree such as an AVL or red-black tree, or a treap, storing subtree aggregates. Where data never changes, a sparse table answers idempotent queries such as minimum in O(1).

Applications

Fenwick introduced his tree in 1994 for adaptive arithmetic coding, where the compressor must update a symbol's frequency and read cumulative frequencies after every symbol; both operations dropped from linear to logarithmic. Bentley's original segment tree solved Klee's problem of measuring the union of rectangles with a sweep line, and it remains the standard method in computational geometry for stabbing and windowing queries.

Beyond those, the sources reviewed for this chapter do not identify a production system that documents a range-aggregate segment tree in a specific component. The structure is ubiquitous in algorithm courses and programming contests, and analytical databases solve similar problems with block summaries such as zone maps rather than per-element trees.

Summary

A segment tree stores the aggregate of every interval in a complete binary tree over an array, laid out in a flat array of 2n slots. A point update rewrites one leaf and its log₂ n ancestors; a range query combines at most two nodes per level from the canonical decomposition; lazy tags extend both to range updates.

Everything is O(log n) worst-case for any associative operation, at a cost of extra memory and more code than a Fenwick tree, which suffices when the operation is invertible. Path copying makes the tree persistent, and a root-to-leaf descent answers prefix searches in a single pass.

The Segment Tree: Precomputed answers for every power-of-two interval, so that any range is a handful of reads
The Segment Tree — Precomputed answers for every power-of-two interval, so that any range is a handful of reads.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Fenwick, P. M. (1994). A new data structure for cumulative frequency tables. Software: Practice and Experience, 24(3), 327–336. doi.org/10.1002/spe.4380240306
  2. de Berg, M., Cheong, O., van Kreveld, M., & Overmars, M. (2008). Computational Geometry: Algorithms and Applications (3rd ed.), ch. 10. Springer. doi.org/10.1007/978-3-540-77974-2
  3. Driscoll, J. R., Sarnak, N., Sleator, D. D., & Tarjan, R. E. (1989). Making data structures persistent. Journal of Computer and System Sciences, 38(1), 86–124. doi.org/10.1016/0022-0000(89)90034-2

Applications and implementations

  1. Al.Cash (2015). Efficient and easy segment trees — the bottom-up 2n layout. codeforces.com/blog/entry/18051
  2. Witten, I. H., Neal, R. M., & Cleary, J. G. (1987). Arithmetic coding for data compression. Communications of the ACM, 30(6), 520–540. doi.org/10.1145/214762.214771

Enjoyed this chapter? Support The Ledger.