Fenwick Trees
Binary Indexed Tree
A Fenwick Tree (BIT) answers prefix-sum queries and handles point updates in O(log n) using just an array and the low-bit trick — simpler and faster in practice than a segment tree for pure prefix sums.
What is a Fenwick tree (binary indexed tree)?
A Fenwick tree, or binary indexed tree, is a compact array-based structure for prefix sums with updates. Both "add x to element i" and "sum of the first i elements" take O(log n), using the lowest set bit of the index (i & -i) to jump between responsible ranges. Range sums are the difference of two prefix sums.
class Fenwick {
constructor(n) { this.tree = new Array(n + 1).fill(0); } // 1-indexed
add(i, delta) { for (i++; i < this.tree.length; i += i & -i) this.tree[i] += delta; }
prefix(i) { let s = 0; for (i++; i > 0; i -= i & -i) s += this.tree[i]; return s; } // sum[0..i]
range(l, r) { return this.prefix(r) - (l ? this.prefix(l - 1) : 0); }
}The low-bit trick
i & (-i) isolates the lowest set bit of i. This maps each index to the range of elements it is responsible for.
Build and query — animated
// Array state
// Pseudocode
Complexity
Linear time
Logarithmic time
Logarithmic time
Linear time
Update
1// Fenwick Tree update — O(log n)2function update(bit, i, delta):3 i = i + 1 // 1-indexed4 while i <= len(bit):5 bit[i] += delta6 i += i & (-i) // add lowest set bit
Query
1// Prefix sum query — O(log n)2function query(bit, i):3 i = i + 1 // 1-indexed4 sum = 05 while i > 0:6 sum += bit[i]7 i -= i & (-i) // remove lowest set bit8 return sum910// Range sum [l, r]:11function rangeQuery(bit, l, r):12 return query(bit, r) - query(bit, l - 1)
🎯 Quick Check
What does i &= (-i) do in the query traversal?
Fenwick Trees: summary
Key points
- Only about 10 lines of code, using O(n) memory.
- Common uses: counting inversions, frequency tables, leaderboard ranks.
Frequently asked questions
›Why is it called a binary indexed tree?
Each index's binary representation decides which range of elements it stores, and the tree structure is implicit in those bit patterns.