06. Range Sum Query - Mutable (Segment Tree / Fenwick Tree)

Difficulty:HardPattern:Fenwick Tree / Segment TreeTime:O(log n) Update/QuerySpace:O(n)

Given an integer array nums, handle multiple queries of updating an element value and calculating the sum of elements between indices left and right inclusive.

How It Works & Algorithmic Design

Solves using a Binary Indexed Tree (Fenwick Tree / BIT):

  1. BIT Mechanics: Array tree of size $n+1$ storing prefix sums. Index index relationships use lowest set bit: i & (-i).
  2. update(index, val):
    • Delta = val - nums[index].
    • nums[index] = val.
    • Loop $i = \text{index} + 1$ up to $n$: tree[i] += delta, advance i += i & (-i).
  3. sumRange(left, right):
    • Query prefix sum $Q(x)$: sum tree[i] stepping down i -= i & (-i).
    • Return $Q(\text{right} + 1) - Q(\left\text{left}\right)$.

Why This Approach Works Best

Achieves logarithmic $O(\log n)$ time for both updates and range sum queries with minimal $O(n)$ space.

Example Walkthrough

Operations

nums = [1,3,5] -> sumRange(0,2) -> update(1,2) -> sumRange(0,2)

Dynamic range queries.

Results

sumRange(0,2)=9. After update index 1 to 2, sumRange(0,2)=8.

Updated sum range.

Output

[9, 8]

Query outputs.

Answer: Fenwick Tree / Binary Indexed Tree implementation

class NumArray {
  constructor(nums) {
    this.n = nums.length;
    this.nums = [...nums];
    this.tree = new Array(this.n + 1).fill(0);
    for (let i = 0; i < this.n; i++) {
      this._initAdd(i + 1, nums[i]);
    }
  }
  _initAdd(i, val) {
    while (i <= this.n) {
      this.tree[i] += val;
      i += i & (-i);
    }
  }
  update(index, val) {
    const delta = val - this.nums[index];
    this.nums[index] = val;
    let i = index + 1;
    while (i <= this.n) {
      this.tree[i] += delta;
      i += i & (-i);
    }
  }
  _prefixSum(i) {
    let sum = 0;
    while (i > 0) {
      sum += this.tree[i];
      i -= i & (-i);
    }
    return sum;
  }
  sumRange(left, right) {
    return this._prefixSum(right + 1) - this._prefixSum(left);
  }
}

Construct Binary Indexed Tree using bitwise least significant bit operations for dynamic range sums.

Key Takeaways
  • Fenwick Tree allows $O(\log n)$ point updates and $O(\log n)$ range queries.

  • Bitwise lowest set bit operator i & (-i) navigates tree parent/child paths.

  • Simpler to write than 4x size Segment Trees.