Fenwick Tree Prefix Sums
Support point updates and range-sum queries in logarithmic time with a compact binary indexed tree and low-bit navigation.
Code
struct Fenwick {
tree: Vec<i64>,
}
impl Fenwick {
fn new(size: usize) -> Self {
Self {
tree: vec![0; size + 1],
}
}
fn add(&mut self, mut index: usize, delta: i64) {
index += 1;
while index < self.tree.len() {
self.tree[index] += delta;
index += index & index.wrapping_neg();
}
}
fn prefix_sum(&self, mut index: usize) -> i64 {
let mut total = 0;
while index > 0 {
total += self.tree[index];
index -= index & index.wrapping_neg();
}
total
}
fn range_sum(&self, left: usize, right: usize) -> i64 {
self.prefix_sum(right) - self.prefix_sum(left)
}
}
fn main() {
let values = [3, 2, -1, 6, 5, 4, -3, 3, 7, 2, 3];
let mut tree = Fenwick::new(values.len());
for (index, value) in values.iter().enumerate() {
tree.add(index, *value);
}
println!("sum 0..5 = {}", tree.range_sum(0, 5));
println!("sum 3..8 = {}", tree.range_sum(3, 8));
tree.add(4, 10);
println!("after update 0..5 = {}", tree.range_sum(0, 5));
}
How it works
The working surface is the functions new, add, prefix_sum and range_sum — everything else is wiring.
Iteration happens inside while index < self.tree.len() — everything outside it runs once.
Using it
Entry signature: fn new(size: usize) -> Self
The demo output is labeled (sum 0..5 =, sum 3..8 =, after update 0..5 =), so every printed line maps back to its originating operation.
Running the file executes main, which drives new, add and range_sum in order.
Key statements
fn range_sum(&self, left: usize, right: usize) -> i64 {
self.prefix_sum(right) - self.prefix_sum(left)
}
fn add(&mut self, mut index: usize, delta: i64) {
index += 1;
while index < self.tree.len() {
self.tree[index] += delta;
index += index & index.wrapping_neg();
}
}
for (index, value) in values.iter().enumerate() {
tree.add(index, *value);
}
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.Markdown Heading OutlineExtract ATX headings from Markdown into an indented outline with line numbers and per-level counts, ignoring code fences.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Fenwick Tree Prefix Sums print when run?
- The script runs standalone; its 3 labeled outputs include `sum 0..5 =`, `sum 3..8 =`, `after update 0..5 =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.