Sub topic 3
Which operations work: associativity and identity
This chapter assumes you know Big-O notation, basic recursion, and how a binary tree stores a parent with two children. Segment trees only work when the question you ask meets two rules. This chapter states those rules and shows how to check them.
Why the tree needs rules
A segment tree stores the answer for a segment in each node. A parent's answer is built by combining its two children's answers. A query then glues together a few stored answers that cover the range. For this to give the right result, the combining operation must behave well.
Call the operation op. A monoid is a set of values with an op that has two properties:
- Associativity:
op(op(a, b), c) == op(a, op(b, c)). Grouping does not change the result. - Identity: there is a value
ewithop(e, x) == xandop(x, e) == xfor everyx. The identity is the answer for an empty segment.
Associativity matters because the tree decides the grouping, not you. The same range can be split as (a, b), c in one tree shape and a, (b, c) in another. The result must not depend on the split.
The identity matters for two reasons. A query returns it for a node whose segment lies completely outside the range, which is the return 0 line in the sum tree. It also pads the array when the size is not a power of two.
Common operations
| Operation | `op` | Identity `e` |
|---|---|---|
| Sum | `a + b` | `0` |
| Product | `a * b` | `1` |
| Minimum | `min(a, b)` | `+infinity` |
| Maximum | `max(a, b)` | `-infinity` |
| GCD | `gcd(a, b)` | `0` |
| XOR | `a ^ b` | `0` |
The next program checks both laws on a sample array. It splits the array into two halves, combines the halves, and compares the result with a left-to-right fold.
import math
from functools import reduce
a = [5, 2, 7, 1, 3]
ops = {
"sum": (lambda x, y: x + y, 0),
"min": (min, math.inf),
"max": (max, -math.inf),
"gcd": (math.gcd, 0),
}
for name, (op, e) in ops.items():
left = reduce(op, a[:2], e)
right = reduce(op, a[2:], e)
whole = reduce(op, a, e)
print(name, op(left, right) == whole, op(e, whole) == whole)Every line prints True True. The first value shows that splitting does not change the answer. The second shows that the identity changes nothing.
An operation that fails
Subtraction is not associative. (5 - 2) - 7 is -4, but 5 - (2 - 7) is 10. A segment tree over subtraction would return different answers depending on how it split the range, so it is not valid. Averages fail the same way. You can still compute an average by storing a (sum, count) pair, because adding pairs is associative.
Order and commutativity
Commutative means op(a, b) == op(b, a). The segment tree does not require it. String concatenation is associative but not commutative, and a segment tree handles it if every combine puts the left child first and the right child second. Keep that order in your code. Many order bugs appear only for non-commutative operations, because the sum, min, and max tests cannot reveal them.
Fenwick trees need more
A Fenwick tree answers range queries by subtracting two prefix answers. That needs an inverse, so every value x must have a partner that cancels it. Sum and XOR have inverses. Min and max do not. A later chapter covers this limit in the choice between the two structures.
Exercise
Is "return the left value, ignore the right" (op(a, b) = a) valid for a segment tree? Check associativity and look for an identity.
Show answer
It is associative: op(op(a, b), c) = a and op(a, op(b, c)) = a. It has no true identity. op(e, x) = e, which is not x for every x. You can still use it by marking "empty" with a special sentinel such as None and treating it as the identity in code. The result is a tree that returns the first element of a range.