The Fenwick Tree is a data structure that maintains an array of integers by maintaining

which costs a space of .

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

Lemma

Applying the lemma to find yields an algorithm that 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;
}