Fenwick trees
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)A Fenwick tree, or Binary Indexed Tree (BIT), supports point updates and prefix sum queries in logarithmic time using just a single 1D array. We start with binary representation to see how lowest set bits structure interval coverage.
The Lowest Set Bit and Interval Coverage
A Fenwick tree (binary indexed tree) stores partial sums in an array so that prefix sums and single updates both take O(log n) with very little code.
How can a 1D array of size N store partial sums so that both prefix queries and point updates take O(log N) time? The answer lies in the binary representation of integers.
Example 1 · Lowest set bit: O(1) per number
public class LowbitInspectionDemo { public static void main(String[] args) { for (int i = 1; i <= 8; i++) { System.out.println("i=" + i + " (" + Integer.toBinaryString(i) + ") -> lowbit=" + (i & (-i))); } }}i=1 (1) -> lowbit=1 i=2 (10) -> lowbit=2 i=3 (11) -> lowbit=1 i=4 (100) -> lowbit=4 i=5 (101) -> lowbit=1 i=6 (110) -> lowbit=2 i=7 (111) -> lowbit=1 i=8 (1000) -> lowbit=8
What this code does
- Odd numbers have lowest set bit 1.
- Multiples of 4 have lowest set bit >= 4.
- Power of 2 numbers have lowbit equal to themselves.
Every positive integer i can be uniquely decomposed into powers of two. The lowest set bit of i is isolated using the bitwise formula: lowbit(i) = i & (-i). In a Fenwick tree, entry tree[i] stores the sum of elements in the half-open interval (i - lowbit(i), i]. For example, 12 is binary 1100; its lowbit is 4, so tree[12] stores the sum of 4 elements ending at index 12: elements (8, 12].
Predict the output
Predict the lowest set bit
Think in binary, then pick what is printed.
Round 1 of 3
Prefix Sum Query: Stripping Lowest Set Bits
A prefix sum query on a Fenwick tree adds tree[i] to the sum and then strips the lowest set bit of i with i -= i & (-i). For query(7) it reads only three cells (shown after the code).
public class FenwickQueryPath { public static void main(String[] args) { int i = 7; StringBuilder path = new StringBuilder(); while (i > 0) { path.append(i).append(" (").append(Integer.toBinaryString(i)).append(") "); i -= i & (-i); // strip the lowest set bit } System.out.println("query(7) reads tree at: " + path.toString().trim()); }}query(7) reads tree at: 7 (111) 6 (110) 4 (100)
We repeat this process until i becomes 0. Because stripping the lowest set bit removes a set bit at each step, and an integer <= N has at most floor(log2 N) set bits, the query runs in O(log N) operations!
To compute an arbitrary range sum [L, R], we evaluate prefix(R) - prefix(L - 1) in two fast logarithmic passes. The code requires no recursion, no child pointers, and only 4 lines of code.
Point Update: Adding Lowest Set Bits
When an element at index i increases by delta, which tree entries must be updated? Every tree entry whose responsible interval covers index i must receive delta.
Fenwick update: add 6 at index 3
Step 1 of 6
- delta
- 6
Example 2 · Prefix sums on a plain array, brute force: O(N) query, O(1) update
public class PlainArrayDemo { public static void main(String[] args) { int[] vals = {0, 1, 3, 5, 7, 9, 11}; // 1-based: indices 1..6 System.out.println("Prefix sum [1..4]: " + prefix(vals, 4)); System.out.println("Range sum [2..5]: " + (prefix(vals, 5) - prefix(vals, 1))); vals[3] += 6; // update is one step: O(1) System.out.println("Range sum [2..5] after update: " + (prefix(vals, 5) - prefix(vals, 1))); }
static int prefix(int[] vals, int i) { int sum = 0; for (int k = 1; k <= i; k++) sum += vals[k]; // every query adds up to N cells return sum; }}Prefix sum [1..4]: 16 Range sum [2..5]: 24 Range sum [2..5] after update: 30
What this code does
- An update changes one cell: O(1).
- A prefix query adds up to N cells, and a range query is the difference of two prefix queries.
- It prints 16, 24 and 30, the same as the Fenwick tree.
Example 3 · Fenwick tree, optimal: O(log N) query and update, O(N) space
public class FenwickTreeDemo { private int[] tree; private int n;
public FenwickTreeDemo(int n) { this.n = n; tree = new int[n + 1]; // 1-based indexing }
public void update(int i, int delta) { while (i <= n) { tree[i] += delta; i += i & (-i); // add lowest set bit } }
public int query(int i) { int sum = 0; while (i > 0) { sum += tree[i]; i -= i & (-i); // strip lowest set bit } return sum; }
public int rangeQuery(int l, int r) { return query(r) - query(l - 1); }
public static void main(String[] args) { FenwickTreeDemo bit = new FenwickTreeDemo(6); // Array: {1, 3, 5, 7, 9, 11} at 1-based indices 1..6 int[] vals = {1, 3, 5, 7, 9, 11}; for (int i = 0; i < vals.length; i++) bit.update(i + 1, vals[i]);
System.out.println("Prefix sum [1..4]: " + bit.query(4)); System.out.println("Range sum [2..5]: " + bit.rangeQuery(2, 5)); bit.update(3, 6); // add 6 to index 3 (5 becomes 11) System.out.println("Range sum [2..5] after update: " + bit.rangeQuery(2, 5)); }}Prefix sum [1..4]: 16 Range sum [2..5]: 24 Range sum [2..5] after update: 30
What this code does
- Prefix sum [1..4] = 1 + 3 + 5 + 7 = 16.
- Range sum [2..5] = 3 + 5 + 7 + 9 = 24.
- Adding 6 to index 3 increases range sum to 24 + 6 = 30. Both query and update run in strictly O(log N) time.
- Why faster: each cell stores a block of 2^k elements, so a query or an update touches about log2(N) cells instead of N.
Remarkably, the next covering entry is obtained by adding the lowest set bit: i += i & (-i). We add delta to tree[i], advance i, and repeat while i <= N. Just like the query, this traversal visits at most floor(log2 N) entries, executing point updates in strictly O(log N) time. The entire data structure requires only N + 1 elements, using 1/4 the memory of a segment tree.
Classic Application: Counting Array Inversions
An inversion is a pair of indices (i, j) such that i < j but arr[i] > arr[j]. Inversion count measures how far an array is from being sorted.
Example 4 · Counting inversions pair by pair, brute force: O(N²) time, O(1) space
public class InversionPairsDemo { static int countInversions(int[] arr) { int count = 0; for (int i = 0; i < arr.length; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) count++; // check every pair } } return count; }
public static void main(String[] args) { System.out.println("Inversions in {8, 4, 2, 1}: " + countInversions(new int[]{8, 4, 2, 1})); System.out.println("Inversions in {3, 1, 2}: " + countInversions(new int[]{3, 1, 2})); }}Inversions in {8, 4, 2, 1}: 6
Inversions in {3, 1, 2}: 2What this code does
- The two loops compare arr[i] with every later element arr[j].
- An inversion is a pair with i < j and arr[i] > arr[j].
- It prints 6 and 2, the same as the Fenwick version, but a million elements need about 5 · 10^11 comparisons.
Example 5 · Counting inversions with a Fenwick tree, optimal: O(N log N) time, O(N) space
import java.util.Arrays;
public class InversionCountFenwickDemo { static class SimpleBIT { int[] tree; int n; SimpleBIT(int n) { this.n = n; tree = new int[n + 1]; } void update(int i, int delta) { for (; i <= n; i += (i & -i)) tree[i] += delta; } int query(int i) { int sum = 0; for (; i > 0; i -= (i & -i)) sum += tree[i]; return sum; } }
public static long countInversions(int[] arr) { int n = arr.length; int[] sorted = arr.clone(); Arrays.sort(sorted);
SimpleBIT bit = new SimpleBIT(n); long inversions = 0;
for (int i = n - 1; i >= 0; i--) { // Coordinate compression: rank of arr[i] (1-based) int rank = Arrays.binarySearch(sorted, arr[i]) + 1; inversions += bit.query(rank - 1); bit.update(rank, 1); } return inversions; }
public static void main(String[] args) { int[] arr = {8, 4, 2, 1}; System.out.println("Inversions in {8, 4, 2, 1}: " + countInversions(arr)); int[] arr2 = {3, 1, 2}; System.out.println("Inversions in {3, 1, 2}: " + countInversions(arr2)); }}Inversions in {8, 4, 2, 1}: 6
Inversions in {3, 1, 2}: 2What this code does
- {8, 4, 2, 1} is reversed, containing 4 * 3 / 2 = 6 inversions.
- {3, 1, 2} has inversions (3, 1) and (3, 2) = 2 inversions.
- Scans right-to-left and queries elements smaller than current element in O(log N).
- Why faster: for each element one Fenwick query counts the earlier larger values, replacing the inner loop over all earlier elements.
While merge sort counts inversions in O(N log N) time, a Fenwick tree solves it dynamically in a single scan. We traverse the array from right to left, query the Fenwick tree for the count of numbers smaller than arr[i], and then insert arr[i] into the tree. Combined with coordinate compression when numbers can be large or negative, the Fenwick tree counts inversions in O(N log N) time with unmatched code simplicity.
Next step
Check your understanding
10 quick questions