Segment Tree in Data Structure — Operations, Advantages and Disadvantages
A Segment Tree is a binary tree used to store information about intervals (segments) of an array, enabling efficient range queries (such as range sum, minimum, or maximum) and point/range updates.
Structure
Each leaf node represents a single array element, and each internal node represents the combined result (e.g., sum) of its children's ranges. The root represents the entire array's range.
class SegmentTree:
def __init__(self, arr):
n = len(arr)
self.n = n
self.tree = [0] * (2 * n)
for i in range(n):
self.tree[n + i] = arr[i]
for i in range(n - 1, 0, -1):
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def update(self, index, value):
i = index + self.n
self.tree[i] = value
while i > 1:
i //= 2
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def range_sum(self, left, right): # [left, right)
left += self.n
right += self.n
total = 0
while left < right:
if left % 2 == 1:
total += self.tree[left]; left += 1
if right % 2 == 1:
right -= 1; total += self.tree[right]
left //= 2; right //= 2
return total
Complexity
| Operation | Time |
|---|---|
| Build | O(n) |
| Range Query | O(log n) |
| Point Update | O(log n) |
Advantages
- Efficient range queries and updates in logarithmic time.
- Flexible — can be adapted for sum, min, max, GCD and other associative operations.
Disadvantages
- More complex to implement than simpler structures like prefix sums.
- Uses roughly 2x-4x the memory of the original array.
- Not ideal when the array changes size frequently (rebuilding is costly).
Applications
- Range sum/min/max queries in competitive programming.
- Interval scheduling problems.
- Computational geometry algorithms.
Lazy Propagation for Range Updates
The basic tree updates one element at a time. But many problems ask you to add a value to a whole range at once, and doing that leaf by leaf costs O(n). Lazy propagation fixes this: when a range update covers an entire node, you record the pending change on that node and stop, instead of recursing into every child. The stored "lazy" value is only pushed down when a later query actually needs those children. This keeps range updates at O(log n).
# sketch of a lazy update
def update_range(node, lo, hi, l, r, val):
if r < lo or hi < l: # no overlap
return
if l <= lo and hi <= r: # full overlap: mark lazy, stop
apply(node, val)
lazy[node] += val
return
push_down(node) # move pending work to children first
# recurse into both halves, then recombine
Walking a Range Query Up the Tree
The iterative query in the sample climbs from the leaves toward the root. When the current left index is a right child (odd), its value belongs to the answer and the pointer moves right. When the right index is a right child, it steps left and includes that node. Halving both pointers each round moves up one level, so the range is covered by at most two nodes per level — that is why a query touches only O(log n) nodes rather than every element in the range.
Segment Tree vs Fenwick Tree and Prefix Sums
| Structure | Range query | Update | Best for |
|---|---|---|---|
| Prefix sum array | O(1) | O(n) | Data that never changes |
| Fenwick (BIT) | O(log n) | O(log n) | Sums with point updates, less code |
| Segment tree | O(log n) | O(log n) | Min, max, gcd, assignments, range updates |
Use a prefix sum when the array is static. Use a Fenwick tree when you only need sums with point updates and want simpler code. Reach for a segment tree when you need richer operations or range updates, which is where its extra memory and complexity pay off.
The flexibility comes from one requirement: the operation you combine children with must be associative, meaning the grouping of combines does not change the result. Sum, minimum, maximum and gcd all qualify, which is why one segment tree template handles them by swapping only the merge step. An operation that is not associative cannot be split and recombined this way, so it does not fit the structure — a useful test before you try to force a problem onto a segment tree.
Takeaway: a segment tree earns its weight when data changes and you query ranges. Add lazy propagation for range updates, and remember that for plain changing sums a Fenwick tree is often the lighter choice.