QA
Intermediate LevelData Structures & Algorithms

What is a Fenwick Tree (Binary Indexed Tree) and how does it work?

ā“ Interview Prompt: Explain Binary Indexed Tree (BIT/Fenwick Tree), O(log N) prefix sum and point update operations, and the lowbit trick.

A Fenwick Tree (BIT) provides $O(\log N)$ prefix sum queries and point updates, with $O(N)$ space — simpler to implement than a Segment Tree.

Core Idea: Lowbit Trick

Each index $i$ is responsible for a range of length equal to its lowest set bit (i & (-i)).

•
Update: Add delta to index $i$ and propagate to all ancestors: i += i & (-i).
•
Query (prefix sum 1..i): Sum contributions while moving to parent: i -= i & (-i).

Code Implementation Example

typescript
class FenwickTree {
  private tree: number[];
  constructor(private n: number) {
    this.tree = new Array(n + 1).fill(0);
  }

  update(i: number, delta: number): void { // 1-indexed
    for (; i <= this.n; i += i & (-i))
      this.tree[i] += delta;
  }

  query(i: number): number { // prefix sum [1..i]
    let sum = 0;
    for (; i > 0; i -= i & (-i))
      sum += this.tree[i];
    return sum;
  }

  rangeQuery(l: number, r: number): number {
    return this.query(r) - this.query(l - 1);
  }
}
šŸ’”Fenwick Tree with O(log N) point update and prefix sum query.
šŸŽÆ Interview Key Takeaway

Fenwick Tree is simpler to code than a Segment Tree but limited to associative-invertible operations (sum, XOR). Not suitable for range min/max without modifications.

#DSA#Fenwick Tree#BIT#Range Queries#Intermediate
Back to all Data Structures & Algorithms Questions→

More Data Structures & Algorithms Interview Questions

Beginner LevelData Structures & Algorithms

What is the difference between an Array and a Linked List?

Beginner LevelData Structures & Algorithms

What is Big-O Notation and why is it important?

Beginner LevelData Structures & Algorithms

What are Stack and Queue data structures and where are they used?