Segment tree
A segment tree stores an answer (a sum, a minimum, a maximum) for every segment in a halving hierarchy of an array. Any range splits into O(log n) stored segments, so range queries and single-element updates both take O(log n). The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.
How to recognise it
- Many range queries mixed with updates to single elements.
- Prefix sums are too slow because values change.
- Range minimum, maximum, sum, GCD or any associative combine.
The structure
Node 1 covers the whole array; node k covers a segment and its children 2k and 2k + 1 cover its halves. Leaves are the single elements.
build(k, lo, hi): if lo == hi: t[k] = a[lo] else build halves; t[k] = combine(t[2k], t[2k+1])
query(k, lo, hi, l, r):
if r < lo or hi < l: identity
if l <= lo and hi <= r: t[k]
else combine(query(left half), query(right half))
update(k, lo, hi, i, v): go down to leaf i, set it, recombine on the way up
| Operation | Time |
|---|---|
| build | O(n) |
| range query | O(log n) |
| point update | O(log n) |
Common mistakes
- An identity value that is not neutral (0 for sums, +infinity for minimums).
- Too small an array: use 4n.
Problems
No problems listed for this pattern yet.