Fenwick Tree Implementation in JavaScript
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 JavaScript as in every other language.
- ✓No Fenwick anywhere, so the real decision is the backing buffer. A plain Array holds float64, exact only while every stored prefix stays under Number.MAX_SAFE_INTEGER.
- ✓Reviewers want the buffer type chosen from the value range and stated in a comment, #private class fields for the length and the tree, i & -i inline in the for-loop header rather than behind a lowbit helper, and a zero-based public API.
- ✓The JavaScript trap: Every bitwise operator coerces its operands to signed 32-bit, so i & -i truncates past 2^31 - 1, though you need two billion elements to feel that.
- ✓The walk is about twenty iterations at a million elements and JITs close to native once the element type stays monomorphic; if the tree is sometimes an Array and sometimes an Int32Array the access site goes megamorphic and you lose most of that.
What Fenwick Tree actually is
Fenwick Tree in JavaScript: what you actually reach for
JavaScript implementation
class FenwickTree {
#n;
#tree;
constructor(values) {
this.#n = values.length;
this.#tree = new Int32Array(this.#n + 1); // 1-based, wraps deterministically
this.#tree.set(values, 1);
for (let i = 1; i <= this.#n; i++) {
const j = i + (i & -i);
if (j <= this.#n) this.#tree[j] += this.#tree[i];
}
}
add(idx, delta) {
if (!Number.isInteger(idx) || idx < 0 || idx >= this.#n) {
throw new RangeError(`index ${idx}`);
}
for (let i = idx + 1; i <= this.#n; i += i & -i) this.#tree[i] += delta;
}
prefix(count) {
let sum = 0;
for (let i = count; i > 0; i -= i & -i) sum += this.#tree[i];
return sum;
}
rangeSum(lo, hi) {
return this.prefix(hi) - this.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 JavaScript-specific trap
Performance in JavaScript, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Fenwick Tree?
No Fenwick anywhere, so the real decision is the backing buffer. A plain Array holds float64, exact only while every stored prefix stays under Number.MAX_SAFE_INTEGER. Int32Array gives contiguous memory and deterministic 32-bit wraparound, Float64Array keeps exact integers to 2^53, and BigInt64Array removes the ceiling but allocates a BigInt on every element read. structuredClone deep-copies a typed array. Atomics.add over an Int32Array backed by a SharedArrayBuffer is the only way to share one tree across Workers.
What is the most common JavaScript mistake when implementing Fenwick Tree?
Every bitwise operator coerces its operands to signed 32-bit, so i & -i truncates past 2^31 - 1, though you need two billion elements to feel that. The one that actually bites is that your values are float64: while a running prefix stays inside plus or minus 2^53 the additions are exact, and past it tree[i] += delta silently rounds, so prefix sums stop being reproducible with no exception and no NaN to catch. Int32Array at least wraps deterministically. Adding a BigInt delta into a Number tree throws TypeError: Cannot mix BigInt and other types.
How does Fenwick Tree actually perform in JavaScript?
The walk is about twenty iterations at a million elements and JITs close to native once the element type stays monomorphic; if the tree is sometimes an Array and sometimes an Int32Array the access site goes megamorphic and you lose most of that. A typed array keeps the whole structure inside one ArrayBuffer, so the walk touches roughly log2(n) cache lines. The runtime is single threaded, so a batch of a million updates blocks the event loop: chunk it, or move the tree into a Worker over SharedArrayBuffer. 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 trialStudying for this? GitHub Copilot free tiers and academic plans are laid out 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.