Reading history

Fenwick Tree (Binary Indexed Tree) in C

6 min read 1 views

Learn the Fenwick tree in C: how i & -i works, prefix and range sums with O(log n) updates, counting inversions and live rankings.

A Fenwick tree, also called a binary indexed tree (BIT), keeps running totals of an array so that you can update a value and ask for a prefix sum, both in O(log n) time. It does the same job as a segment tree for sums, but with an array of only n + 1 integers and two loops of about three lines each. The trick is a single bit operation, i & -i, which decides which part of the array each cell is responsible for.

In this lesson you will learn

  • How i & -i finds the lowest set bit
  • Which range each Fenwick cell covers
  • Point updates and prefix sums in O(log n)
  • Range sums from two prefix sums
  • Counting inversions and live rankings with a Fenwick tree

You should know prefix sums and bit manipulation basics.

Updates and Prefix Sums

#include <stdio.h>

#define N 8

static int bit[N + 1];            /* Fenwick tree, 1-indexed */

/* i & -i keeps only the lowest set bit of i */
static void add(int i, int delta) {
    for (; i <= N; i += i & -i) bit[i] += delta;
}

static int prefix_sum(int i) {    /* sum of a[1..i] */
    int s = 0;
    for (; i > 0; i -= i & -i) s += bit[i];
    return s;
}

static int range_sum(int l, int r) { return prefix_sum(r) - prefix_sum(l - 1); }

int main(void) {
    int a[N + 1] = {0, 5, 3, 8, 6, 1, 4, 7, 2};      /* a[0] unused */
    for (int i = 1; i <= N; i++) add(i, a[i]);

    printf("i      :");
    for (int i = 1; i <= N; i++) printf("%4d", i);
    printf("\ncovers :");
    for (int i = 1; i <= N; i++) printf("%4d", i & -i);  /* how many elements bit[i] holds */
    printf("\nbit[i] :");
    for (int i = 1; i <= N; i++) printf("%4d", bit[i]);
    printf("\n\n");

    printf("sum a[1..5] = %d\n", prefix_sum(5));
    printf("sum a[3..6] = %d\n", range_sum(3, 6));
    add(5, 9);                                        /* a[5] goes from 1 to 10 */
    printf("after a[5] += 9: sum a[3..6] = %d, total = %d\n", range_sum(3, 6), prefix_sum(N));
    return 0;
}

Output

i      :   1   2   3   4   5   6   7   8
covers :   1   2   1   4   1   2   1   8
bit[i] :   5   8   8  22   1   5   7  36

sum a[1..5] = 23
sum a[3..6] = 19
after a[5] += 9: sum a[3..6] = 28, total = 45
  • The tree uses 1-based indexes. i & -i keeps only the lowest 1 bit of i: for 6 (binary 110) it is 2, for 8 (1000) it is 8. In two’s complement, -i flips all bits of i and adds one, so only that lowest bit survives the AND.
  • bit[i] stores the sum of the last i & -i elements ending at position i. The “covers” row shows this: bit[4] holds a[1..4] = 22, bit[6] holds a[5..6] = 5, and bit[8] holds everything, 36.
  • prefix_sum(i) adds cells while removing the lowest bit each step: for 5 it adds bit[5] and bit[4], giving 1 + 22 = 23.
  • add(i, delta) updates every cell that covers position i, moving up by adding the lowest bit: for 5 it touches cells 5, 6 and 8.
  • Both loops run at most about log2 n times. A range sum is two prefix sums: prefix(r) - prefix(l - 1).
  • Building by calling add for each element takes O(n log n).

Counting Inversions and Ranks

#include <stdio.h>
#include <string.h>

#define MAXV 100

static int bit[MAXV + 1];

static void add(int i, int d) { for (; i <= MAXV; i += i & -i) bit[i] += d; }
static int sum(int i) { int s = 0; for (; i > 0; i -= i & -i) s += bit[i]; return s; }

int main(void) {
    /* Counting inversions: pairs i < j with a[i] > a[j] (how "unsorted" an array is) */
    int a[] = {8, 4, 2, 1};
    int b[] = {3, 1, 2, 5, 4};
    int *arrays[] = {a, b};
    int sizes[] = {4, 5};

    for (int t = 0; t < 2; t++) {
        memset(bit, 0, sizeof bit);
        long inversions = 0;
        for (int i = 0; i < sizes[t]; i++) {
            int v = arrays[t][i];
            inversions += i - sum(v);   /* earlier values greater than v */
            add(v, 1);                  /* record v as seen */
        }
        printf("array %d: %ld inversions\n", t + 1, inversions);
    }

    /* Live ranking: how many scores so far are at or below each new score? */
    memset(bit, 0, sizeof bit);
    int scores[] = {72, 85, 60, 85, 91, 55};
    for (int i = 0; i < 6; i++) {
        add(scores[i], 1);
        printf("score %d: at or above %d of %d scores so far\n", scores[i], sum(scores[i]), i + 1);
    }
    return 0;
}

Output

array 1: 6 inversions
array 2: 3 inversions
score 72: at or above 1 of 1 scores so far
score 85: at or above 2 of 2 scores so far
score 60: at or above 1 of 3 scores so far
score 85: at or above 4 of 4 scores so far
score 91: at or above 5 of 5 scores so far
score 55: at or above 1 of 6 scores so far
  • Here the Fenwick tree is indexed by value, not position. add(v, 1) records that value v has been seen, and sum(v) counts seen values that are at most v.
  • An inversion is a pair that is out of order. When reading the i-th element, i values have been seen and sum(v) of them are not greater than it, so i - sum(v) earlier values are greater. Adding these up counts every inversion in O(n log n).
  • {8, 4, 2, 1} is fully reversed, so every one of its 6 pairs is an inversion. Inversions measure how far an array is from sorted, and equal the number of swaps bubble sort would make.
  • The ranking example answers “how many scores so far are at or below this one?” as each new score arrives, a common task for leaderboards.
  • Values must fit in the tree’s index range (1 to 100 here). For large or negative values, first replace each value by its position in a sorted copy, called coordinate compression.

Fenwick Tree vs Segment Tree

Fenwick treeSegment tree
Memoryn + 1up to 4n
Code sizeVery shortLonger, recursive
Prefix and range sumsO(log n)O(log n)
Range minimum or maximum with updatesAwkwardEasy
Range updatesPossible with two treesLazy propagation

Common Mistakes

  1. Using index 0: 0 & -0 is 0, so the update loop never ends. Fenwick trees are 1-based.
  2. Calling add(i, newValue) instead of add(i, newValue - oldValue) when changing a value.
  3. Forgetting to clear the tree between test cases.
  4. Value-indexed trees with values larger than the array, which write out of bounds.

Practice Exercises

Exercise 1. Which cells does add(3, x) update in a tree of size 8?

Show answer

3 → 4 (3 + 1) → 8 (4 + 4). The next step, 16, is past the end.

Exercise 2. Write set_value(i, v) for a tree that also keeps the plain array a[].

Show answer
void set_value(int i, int v) {
    add(i, v - a[i]);
    a[i] = v;
}

Frequently Asked Questions

Why is it called a binary indexed tree?

The parent and child relationships come from the binary representation of the indexes: moving up or down removes or adds the lowest set bit. There are no pointers; the “tree” is implied by the index arithmetic.

Can a Fenwick tree work in two dimensions?

Yes. A 2D Fenwick tree nests the two loops, one per dimension, to answer sums over rectangles of a grid in O(log n × log m) time.

Summary

  • A Fenwick tree stores partial sums whose sizes come from i & -i.
  • Updates add the lowest bit; prefix sums remove it; both are O(log n).
  • Range sum = prefix(r) − prefix(l − 1).
  • Indexed by value, it counts inversions and ranks.

Next: Monotonic Stack in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *