Data Structures · Visualization
Fenwick Tree: Prefix Sum
Fenwick Tree
Computing a prefix sum (the total of all elements from the start up to a given index) is done by starting at that index and repeatedly jumping backward using 'index -= lowest set bit of index', adding up each position visited along the way. Time: O(log n). Space: O(1) extra.
Big-O: Update and prefix-sum queries both O(log n).
Fenwick Tree: Prefix Sum
Fenwick TreeComputing a prefix sum (the total of all elements from the start up to a given index) is done by starting at that index and repeatedly jumping backward using 'index -= lowest set bit of index', adding up each position visited along the way. Because each jump skips over a whole pre-summed range, only about log(n) positions need to be added.
How Prefix Sum Works
- Start at the target index (1-indexed) with a running total of 0.
- Add the value stored at the current position to the running total.
- Move to the previous position by subtracting the lowest set bit of the current index.
- Repeat until the index reaches 0.
Prefix Sum Worked Example
Input: Compute prefix sum up to index 6 in a Fenwick tree
- Add value at position 6, jump to 6 - lowestSetBit(6)=2 → position 4
- Add value at position 4, jump to 4 - lowestSetBit(4)=4 → position 0
- Index reached 0, stop and return the running total
Output: Sum of the first 6 elements
Press ▶ Run to watch it step by step.
def prefix_sum(bit, i):
s = 0
while i > 0:
s += bit[i]
i -= i & -i # walk down
return s
# Sum of a range = prefix(r) - prefix(l-1)
# O(log n)
# example: prefix sum 6Behind 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.
Prefix Sum Time & Space Complexity
When to Use Prefix Sum
- Answering 'total so far' queries instantly on frequently changing data
- Computing range sums by subtracting two prefix sums (prefixSum(r) - prefixSum(l-1))
- Counting elements less than a value seen so far (used in counting inversions)
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.