Build a segment tree from a=[2,5,1,3,7,4] with sum aggregation.
First we query the range [1,4], then perform a point update at index 2.
Step 1 / 12
Step 1 / 12
Segment tree built from a=[2,5,1,3,7,4]. Each internal node stores the sum of its range. Tree nodes: [0,5]→[0,2],[3,5]→[0,1],[2,2],[3,4],[5,5]→[0,0],[1,1],[3,3],[4,4].
Step 2 / 12
Query: compute sum(1,4). The query range [1,4] is highlighted in the source array.
Step 3 / 12
Start at root [0,5]. The query [1,4] partially overlaps, so we recurse into both children.
Step 4 / 12
Left subtree [0,2]: recurse down. Node [0,0] is outside query range – skip it.
Step 5 / 12
Node [1,1] fully inside [1,4] – take value 5. Node [2,2] fully inside – take value 1.
Step 6 / 12
Right subtree [3,5]: node [3,4] fully covered – take sum =10. Node [5,5] outside range – skip.
Step 7 / 12
Result: 5+1+10=16. Three nodes contributed – this is why queries are O(logn).
Step 8 / 12
Now perform a point update: set a[2]=10 (was 1). We walk from the leaf up to root.
Step 9 / 12
Update leaf [2,2]: value changes from 1 to 10.
Step 10 / 12
Update [0,2]: new sum =[0,1].sum+10=7+10=17.
Step 11 / 12
Update root [0,5]: new sum =17+14=31. Point update complete in O(logn).
Step 12 / 12
Final tree reflects the updated array a=[2,5,10,3,7,4] with root sum =31.
Sparse Segment Tree – Dynamic Node Allocation
A sparse segment tree over range [0,7]. Nodes are allocated on-demand as values are inserted.
Step 1 / 12
Step 1 / 12
Sparse segment tree on range [0,7]. Initially only the root [0,7] exists. All other nodes are virtual.
Step 2 / 12
Insert value 5 at position 2. Root [0,7] partially covers – recurse left.
Step 3 / 12
Allocate left child [0,3] on-demand. This node did not exist before.
Step 4 / 12
Recurse into [0,3]: position 2 is in the right half. Allocate [2,3].
Step 5 / 12
Allocate leaf [2,2] for position 2.
Step 6 / 12
Set leaf [2,2]=5, bubble sums up: [2,3]=5, [0,3]=5, [0,7]=5.
Step 7 / 12
Insert value 3 at position 6. Root recurses right this time.
Step 8 / 12
Allocate right child [4,7].
Step 9 / 12
Position 6 is in [6,7]. Allocate [6,7].
Step 10 / 12
Allocate leaf [6,6].
Step 11 / 12
Leaf [6,6]=3. Bubble up: [6,7]=3, [4,7]=3, root [0,7]=8. Two paths allocated, rest of tree stays virtual.
Step 12 / 12
Final state: only 8 nodes allocated out of a potential 15. Sparse trees use O(qlogR) memory instead of O(R).