Fenwick Tree Implementation in Rust
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Fenwick Tree runs in O(log n) time and O(n) space, in Rust as in every other language.
- ✓std has no Fenwick and you would not take a dependency for thirty lines. The structure is Vec<i64>, or Box<[i64]> once built, since it never resizes.
- ✓Reviewers want from_values and with_len constructors, &mut self on updates so exclusivity is enforced by the borrow checker instead of by a comment, an explicit panic or a Result for an out-of-range index, and i & i.wrapping_neg() rather than a cast to isize just to make unary minus compile.
- ✓The Rust trap: Writing -i to get the lowbit does not compile on usize, and the usual fix, casting to isize, quietly reintroduces the sign bug you were avoiding; use wrapping_neg.
- ✓One contiguous allocation with no per-element header, so a million i64 nodes is exactly 8 MB and the walk touches about log2(n) cache lines.
What Fenwick Tree actually is
Fenwick Tree in Rust: what you actually reach for
Rust implementation
pub struct Fenwick {
tree: Vec<i64>, // index 0 unused: 0 & -0 == 0 would never advance
}
impl Fenwick {
pub fn from_values(values: &[i64]) -> Self {
let n = values.len();
let mut tree = vec![0i64; n + 1];
tree[1..=n].copy_from_slice(values);
for i in 1..=n {
let j = i + (i & i.wrapping_neg());
if j <= n {
tree[j] += tree[i];
}
}
Self { tree }
}
pub fn add(&mut self, idx: usize, delta: i64) {
let n = self.tree.len() - 1;
assert!(
idx < n,
"Fenwick::add: index {} out of bounds for length {}",
idx,
n
);
// idx < n, so idx + 1 <= n and cannot overflow in either profile.
let mut i = idx + 1;
while i < self.tree.len() {
self.tree[i] += delta;
i += i & i.wrapping_neg(); // -i does not compile for usize
}
}
pub fn prefix(&self, count: usize) -> i64 {
let mut i = count;
let mut sum = 0i64;
while i > 0 {
sum += self.tree[i];
i -= i & i.wrapping_neg();
}
sum
}
pub fn range_sum(&self, lo: usize, hi: usize) -> i64 {
self.prefix(hi) - self.prefix(lo)
}
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Rust-specific trap
Performance in Rust, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Rust type or library should I use for Fenwick Tree?
std has no Fenwick and you would not take a dependency for thirty lines. The structure is Vec<i64>, or Box<[i64]> once built, since it never resizes. The lowbit matters more than the container: unary minus is not implemented for usize, so the correct expression is i & i.wrapping_neg(), with usize::trailing_zeros available if you want the exponent instead of the mask. checked_add, wrapping_add and saturating_add on the integer types let you choose overflow behaviour explicitly rather than inherit one.
What is the most common Rust mistake when implementing Fenwick Tree?
Writing -i to get the lowbit does not compile on usize, and the usual fix, casting to isize, quietly reintroduces the sign bug you were avoiding; use wrapping_neg. Then overflow behaviour differs by profile: integer overflow panics in a debug build and wraps in release unless you opt in, so an i32 accumulator that wraps harmlessly in your benchmark aborts under cargo test. Bounds checking means an off-by-one at n + 1 panics instead of corrupting memory, but people silence it with a length guard that also swallows the loop's real termination condition: an update loop whose only guard is i < tree.len() does not panic on an out-of-range index, it simply never enters the body and drops the write.
How does Fenwick Tree actually perform in Rust?
One contiguous allocation with no per-element header, so a million i64 nodes is exactly 8 MB and the walk touches about log2(n) cache lines. Each access carries a bounds check that LLVM usually cannot hoist, because the stride depends on the lowbit of the running index; that is a couple of instructions, not a doubling. Build profile dominates everything else: debug adds overflow checks, skips inlining and can run an order of magnitude slower. Vec<i64> is Send and Sync, but &mut self serialises writers by construction. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.