Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Fenwick Tree Implementation in Rust

19 min readadvanced
Website QA and SEO audits

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

A Fenwick tree is not a tree of nodes and pointers at all. It is a flat array of n+1 accumulators in which the tree structure lives entirely in the index bits: position i holds the sum of the half-open range (i - (i & -i), i], where i & -i is the lowest set bit under two's complement negation. A point update walks upward by i += i & -i, a prefix query walks downward by i -= i & -i, and each touches one slot per set bit, so both are O(log n), about twenty steps at a million elements. Range sums are prefix(hi) - prefix(lo), which is exactly why the combining operation must be invertible. Index 0 is unusable because 0 & -0 is 0, so one-based indexing is effectively mandatory. Against a segment tree it is roughly half the memory, needs no recursion and has a far tighter constant, but it cannot answer min or arbitrary non-invertible merges. The eight languages diverge on how the index type behaves under unary minus, on whether overflow wraps, traps or is impossible, and on what an array of integers actually costs in memory.

Fenwick Tree in Rust: what you actually reach for

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.

Rust implementation

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. They reject Rc<RefCell<Vec<i64>>> outright, since a Fenwick has no aliasing at all, and reject get_unchecked until a benchmark shows the bounds check on the lowbit stride actually matters.
rust
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 Free

The Rust-specific 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. 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.

Performance in Rust, beyond the O(log n)

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. The asymptotic cost is the same in every language, O(log n) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Fenwick Tree between languages.

Real-World Applications

Fenwick Tree applies wherever its problem shape appears in your own code. In Rust, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Fenwick Tree helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Fenwick Tree appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Fenwick Tree over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Fenwick Tree to build pattern recognition. In Rust, demonstrate proficiency with ownership system and pattern matching to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Rust code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Most AI and dev tools have a student plan. See which ones and how to claim them on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.