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

Fenwick Tree Implementation in TypeScript

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

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 TypeScript: what you actually reach for

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.

TypeScript implementation

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. They reject any, reject as number scattered through the loop, and reject a non-const enum for the index base when a literal union says it.
typescript
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 Free

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

Performance in TypeScript, beyond the O(log n)

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. 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 TypeScript, 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 TypeScript, demonstrate proficiency with generics and type guards to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic TypeScript code that is both correct and maintainable.

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

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

Before paying for GitHub Copilot, check its student and free-tier options 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.