Data Structures · Visualization
Segment Tree: Update
Segment Tree
Updating a single element in the underlying array means changing that element's leaf value and then re-combining every ancestor on the path back to the root, since their stored summaries all depended on it. Time: O(log n). Space: O(log n) recursion.
Big-O: Build O(n); range query and point update O(log n).
Segment Tree: Update
Segment TreeUpdating a single element in the underlying array means changing that element's leaf value and then re-combining every ancestor on the path back to the root, since their stored summaries all depended on it. Because the tree's height is only O(log n), only a small number of nodes need to be revisited.
How Update Works
- Walk from the root toward the leaf representing the index being updated, choosing left or right based on which half contains that index.
- Once the target leaf is reached, set its value to the new value.
- Walk back up the same path, recombining each ancestor's value from its two children.
- Stop once the root has been updated.
Update Worked Example
Input: Update index 1 (value 4) to 10 in tree over [2, 4, 6]
- Navigate to the leaf for index 1 (value 4), set it to 10
- Recombine its parent [2,10] → 12 (was 6)
- Recombine the root: [2,10]=12 and [6]=6 → root = 18
Output: Root updated from 12 to 18
Press ▶ Run to watch it step by step.
def update(tree, n, pos, val):
i = n + pos
tree[i] = val
i //= 2
while i >= 1:
tree[i] = tree[2*i] + tree[2*i+1]
i //= 2
# O(log n)
# example: update 10 at index 1 on [2, 4, 6]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Update Time & Space Complexity
When to Use Update
- Updating a stock price or sensor reading and refreshing range statistics instantly
- Live leaderboards where a single score changes and range queries must stay accurate
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.