Fenwick Tree Implementation in TypeScript
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 TypeScript as in every other language.
- ✓The runtime surface is exactly JavaScript's: Int32Array, Float64Array and BigInt64Array from the lib.es5 and lib.es2020 declaration files, with no Fenwick anywhere.
- ✓Reviewers want the brand applied at exactly one boundary function that also performs the runtime range check, never by a bare as OneBased at the call sites; private readonly on the buffer field; and no generics here, because a Fenwick over addition is only genuinely generic behind a monoid interface whose call the optimiser then has to devirtualise.
- ✓The TypeScript trap: The brand, the readonly and the private all disappear at emit. The shipped JavaScript is the untyped loop, so a caller in a plain JavaScript package can pass -1 and the update walk spins forever on i = 0; only an explicit runtime throw stops it, never the type.
- ✓Types cost nothing at runtime, because nothing is emitted for them, so a well written Fenwick matches hand written JavaScript exactly.
What Fenwick Tree actually is
Fenwick Tree in TypeScript: what you actually reach for
TypeScript implementation
type OneBased = number & { readonly __oneBased: unique symbol };
export class FenwickTree {
private readonly tree: Int32Array;
constructor(private readonly n: number, values?: ArrayLike<number>) {
this.tree = new Int32Array(n + 1);
if (values) {
this.tree.set(values, 1);
for (let i = 1; i <= n; i++) {
const j = i + (i & -i);
if (j <= n) this.tree[j]! += this.tree[i]!;
}
}
}
// the only place the brand is minted, and it checks at runtime
private toOneBased(idx: number): OneBased {
if (!Number.isInteger(idx) || idx < 0 || idx >= this.n) {
throw new RangeError(`index ${idx}`);
}
return (idx + 1) as OneBased;
}
add(idx: number, delta: number): void {
for (let i: number = this.toOneBased(idx); i <= this.n; i += i & -i) {
this.tree[i]! += delta;
}
}
prefix(count: number): number {
let sum = 0;
for (let i = count; i > 0; i -= i & -i) sum += this.tree[i]!;
return sum;
}
}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 TypeScript-specific trap
Performance in TypeScript, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Fenwick Tree?
The runtime surface is exactly JavaScript's: Int32Array, Float64Array and BigInt64Array from the lib.es5 and lib.es2020 declaration files, with no Fenwick anywhere. What TypeScript adds is compile time only. A branded index type, type OneBased = number & { readonly __brand: unique symbol }, stops an internal one-based index from reaching the zero-based public method. satisfies keeps a config literal narrow without widening it. Enabling noUncheckedIndexedAccess types tree[i] as number | undefined and forces you to acknowledge the bound.
What is the most common TypeScript mistake when implementing Fenwick Tree?
The brand, the readonly and the private all disappear at emit. The shipped JavaScript is the untyped loop, so a caller in a plain JavaScript package can pass -1 and the update walk spins forever on i = 0; only an explicit runtime throw stops it, never the type. The second trap is declaring the field as ArrayLike<number> so it accepts both Array and Int32Array: ArrayLike's index signature is readonly, so tree[i] += delta stops compiling, and people fix that with a cast that also erases every remaining guarantee.
How does Fenwick Tree actually perform in TypeScript?
Types cost nothing at runtime, because nothing is emitted for them, so a well written Fenwick matches hand written JavaScript exactly. What does cost: an interface such as Monoid<T> with a combine method turns each of the twenty iterations into a call the optimiser may not inline; a non-const enum compiles to an object property lookup; and readonly number[] still emits a plain Array, so readonly buys review safety rather than layout. Keep the hot loop monomorphic over one concrete typed array. 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 trialBefore paying for GitHub Copilot, check its student and free-tier options 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.