A Fenwick Tree maintains an array of integers by maintaining
which costs a space of .
Add
This is an algorithm that updates to in time and space.
Lemma
Let , then
Proof
Let , then .
Lemma
Proof
Let , then .
Applying the lemmas yields an algorithm that solves the problem in time and space.
for (int j = i + 1; j <= n; j += j & -j) {
s[j] += x;
}Sum
This is an algorithm that computes in time and space.
Lemma
Applying the lemma yields an algorithm that solves the problem in time and space.
int res = 0;
for (int j = i; j > 0; j -= j & -j) {
res += s[j];
}
return res;