Segment Trees
Range queries and updates in O(log n) — the Swiss army knife for interval-based problems.
A Segment Tree is a powerful data structure used for performing range queries (like finding the sum or minimum in a sub-array) and point updates (changing a value in the array) in time.
sum..
a[] =
30
11
42
13
54
95
26
67
1/14
full segment (counted) recomputed path skipped
segment tree — each node stores the sum of its rangeThe Structure
The tree is built over an underlying array of elements:
- Each leaf node represents a single element from the array.
- Each internal node represents a range and stores a precomputed value for that range (e.g., the sum, min, or max of all elements in ).
- A node’s value is derived from its two children (e.g.,
sum = left.sum + right.sum).
Operations
1. Range Query:
To find the sum of range , you start at the root and descend. If a node’s range is completely inside , you take its value and stop. If it’s partially inside, you visit its children. Because of the tree’s height, you never need to visit more than nodes.
2. Point Update:
When a value changes, only the nodes on the path from the root to the leaf need to be updated. For a tree with elements, this path has length .
Why use a Segment Tree?
- Versus Prefix Sums: A prefix sum array can do range sum queries in , but updating a single value takes . Segment trees handle both in .
- Range Updates: With a technique called Lazy Propagation, you can even update an entire range of elements in time.
Takeaways
- Segment trees store precomputed range data in a binary tree structure.
- They support range queries and point updates in time.
- They are ideal for problems where the data changes frequently.