Fenwick Tree (BIT)
A Fenwick tree (also called a Binary Indexed Tree or BIT) is a data structure that supports prefix sum queries and point updates in \(O(\log n)\) time using a single flat array — no pointers, no explicit tree structure.
Invented by Peter Fenwick in 1994, it achieves the same asymptotic complexity as a segment tree for prefix queries with simpler code and a smaller constant factor. The secret is a clever use of the least significant bit (LSB) of array indices.
The problem it solves
Given an array, you want to:
- Query the prefix sum from index 1 to i: sum(1, i)
- Update a single element: arr[i] += delta
A plain array gives \(O(n)\) query, \(O(1)\) update. Prefix sums give \(O(1)\) query, \(O(n)\) update. A Fenwick tree gives \(O(\log n)\) for both.
← → arrow keys to step · click elements to interact
Fenwick Tree: Update & Prefix Sum
How it works: the lowbit trick
The key operation is lowbit(i) = i & (-i), which extracts the lowest set bit of i. For example: lowbit(6) = 6 & (-6) = 6 & ...11111010 = 000000010 = 2.
Each index i in the BIT array stores the sum of elements in the range [i - lowbit(i) + 1, i]:
- BIT[1] = arr[1] (lowbit(1)=1, covers 1 element)
- BIT[2] = arr[1]+arr[2] (lowbit(2)=2, covers 2 elements)
- BIT[4] = arr[1]+arr[2]+arr[3]+arr[4] (lowbit(4)=4, covers 4 elements)
- BIT[6] = arr[5]+arr[6] (lowbit(6)=2, covers 2 elements)
Prefix sum query
To compute sum(1, i): start at i, add BIT[i], then jump to i - lowbit(i), repeat until i becomes 0.
This touches at most \(\log_2(n)\) indices (each step removes a bit).
Point update
To update arr[i] += delta: start at i, add delta to BIT[i], then jump to i + lowbit(i), repeat until i > n.
Range query
Range sum from l to r: sum(1, r) - sum(1, l-1). Two prefix queries = still \(O(\log n)\).
Fenwick vs. Segment Tree
- Fenwick tree: simpler code, smaller constant, only handles prefix queries and point updates natively
- Segment tree: more flexible (range updates, range min/max), but more code and memory
If you only need prefix sums with point updates, always prefer a Fenwick tree — it's faster in practice and trivial to implement correctly.