Arrays & Hashing · Pattern 24 of 26

Fenwick tree: prefix sums with updates

A Fenwick tree keeps prefix sums that you can update in O(log n). Walk the values in order, and "how many smaller values came before me?" is a prefix query.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Prefix sums while values keep changing
  • Count smaller (or larger) elements before or after each position
  • Pairs or triplets in order across two permutations

The template

Fenwick Tree (BIT)
int[] tree;
void add(int i, int v) { for (i++; i < tree.length; i += i & -i) tree[i] += v; }   // 0-based i
int sum(int i) { int s = 0; for (i++; i > 0; i -= i & -i) s += tree[i]; return s; } // sum of [0..i]

// inversions with a BIT: compress values to ranks, then count bigger values seen so far
long countInversionsBit(int[] a) {
    int[] sorted = Arrays.stream(a).distinct().sorted().toArray();
    tree = new int[sorted.length + 1];
    long inv = 0;
    for (int i = 0; i < a.length; i++) {
        int r = Arrays.binarySearch(sorted, a[i]);
        inv += i - sum(r);                 // seen so far minus those <= a[i]
        add(r, 1);
    }
    return inv;
}

The variations

  1. 1Count with a Fenwick tree

    Map one array into the positions of the other, then for each middle element count smaller values on the left and larger on the right with two BIT passes.

Mistakes to avoid

  • Mixing 0-based input with the 1-based tree: shift by one exactly once.
  • Using raw values as indexes when they are large or negative: compress them to ranks first.
Next: String basics →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.