Data Structures · Visualization
Fenwick Tree: Update
Fenwick Tree
Updating a Fenwick tree means adding a delta (the change in value) to one element, then propagating that change to every position in the tree array that covers this element in its range. Time: O(log n). Space: O(1) extra.
Big-O: Update and prefix-sum queries both O(log n).
Fenwick Tree: Update
Fenwick TreeUpdating a Fenwick tree means adding a delta (the change in value) to one element, then propagating that change to every position in the tree array that covers this element in its range. This is done by starting at the element's index and repeatedly jumping forward using 'index += lowest set bit of index', updating each position visited.
How Update Works
- Start at the index being updated (1-indexed).
- Add the delta value to the current position.
- Move to the next position by adding the lowest set bit of the current index.
- Repeat until the index goes past the end of the array.
Update Worked Example
Input: Add +3 to index 3 in a Fenwick tree of size 8
- Update position 3, jump to 3 + lowestSetBit(3)=1 → position 4
- Update position 4, jump to 4 + lowestSetBit(4)=4 → position 8
- Update position 8, jump to 8 + 8 = 16 → past the end, stop
Output: Positions 3, 4, and 8 updated with the delta
Press ▶ Run to watch it step by step.
def update(bit, n, i, delta):
while i <= n:
bit[i] += delta
i += i & -i # climb up
# O(log n)
# example: update at index 3Behind 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
- Adjusting a running total when a single data point changes
- Real-time inventory or score tracking with fast updates
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.