The Fenwick Tree is a data structure that maintains a sequence of numbers by maintaining

This requires space.

Add

Add updates to in time and space.

Algorithm

Lemma

Let , then

Lemma

Applying the lemmas to update yields an algorithm that solves the problem in time and space.

void add(int i, int x) {
	for (int j = i + 1; j <= n; j += j & -j) {
		s[j] += x;
	}
}

Sum

Sum computes in time and space.

Algorithm

  1. Find recursively.
  2. .

This algorithm solves the problem in time and space.

int sum(int i) {
	int res = 0;
	for (int j = i; j > 0; j -= j & -j) {
		res += s[j];
	}
	return res;
}