Why it matters

Range queries are common: 'total sales between date X and Y', 'max temperature in region R'. Naive is O(n) per query. Segment tree gives O(log n). For many queries, this is orders of magnitude.

Advertisement

The architecture

Build: array of size 2n (roughly). Leaves hold array elements; internal nodes hold aggregate of their range. Build recursively bottom-up in O(n).

Query [l, r]: recurse; if node fully in range, use its aggregate; if partially, recurse to children; if outside, skip.

Segment tree operationsBuildaggregate per rangeQuerycombine overlappingUpdatepropagate to rootLazy propagation defers node updates until needed, enabling O(log n) range updates
Segment tree ops.
Advertisement

How it works end to end

Point update: change leaf, propagate aggregate change up to root. O(log n).

Range update: naive is O(n log n). Lazy propagation stores pending updates at nodes, applies them only when needed. Amortized O(log n).

Fenwick tree (BIT): simpler alternative for prefix-sum queries. Not as general but faster in practice for that use case.