SDE & MLE Prep

307. Range Sum Query - Mutable

Problem

Design NumArray(nums) with update(index, val), which sets nums[index] = val, and sumRange(left, right), which returns the sum of nums[left..right]. Both kinds of calls are frequent.

Example: NumArray([1,3,5]) → sumRange(0,2) = 9; update(1,2) → sumRange(0,2) = 8

Constraints: n ≤ 3·10⁴; up to 3·10⁴ calls.

Point updates break plain prefix sums (O(n) per update). A Fenwick tree stores partial sums over power-of-two ranges: both update and prefix query walk O(log n) nodes. update adds the delta val − nums[i].

Complexity: O(log n) update and query.

class NumArray:
    def __init__(self, nums: List[int]):
        self.n, self.nums = len(nums), nums[:]
        self.t = [0] * (self.n + 1)
        for i, x in enumerate(nums):
            self._add(i + 1, x)

    def _add(self, i, v):
        while i <= self.n:
            self.t[i] += v
            i += i & -i

    def _pre(self, i):
        s = 0
        while i:
            s += self.t[i]
            i -= i & -i
        return s

    def update(self, index: int, val: int) -> None:
        self._add(index + 1, val - self.nums[index])
        self.nums[index] = val

    def sumRange(self, left: int, right: int) -> int:
        return self._pre(right + 1) - self._pre(left)