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)
na = NumArray([1, 3, 5])
assert na.sumRange(0, 2) == 9
na.update(1, 2)
assert na.sumRange(0, 2) == 8 and na.sumRange(1, 1) == 2
class NumArray {
private final int[] t, nums;
private final int n;
public NumArray(int[] nums) {
n = nums.length;
this.nums = nums.clone();
t = new int[n + 1];
for (int i = 0; i < n; i++) add(i + 1, nums[i]);
}
private void add(int i, int v) { for (; i <= n; i += i & -i) t[i] += v; }
private int pre(int i) { int s = 0; for (; i > 0; i -= i & -i) s += t[i]; return s; }
public void update(int index, int val) { add(index + 1, val - nums[index]); nums[index] = val; }
public int sumRange(int left, int right) { return pre(right + 1) - pre(left); }
}
type NumArray struct {
nums []int
tree []int // Fenwick tree, 1-indexed
}
func Constructor(nums []int) NumArray {
na := NumArray{nums: append([]int(nil), nums...), tree: make([]int, len(nums)+1)}
for i, x := range nums {
na.add(i+1, x)
}
return na
}
func (this *NumArray) add(i, v int) {
for ; i < len(this.tree); i += i & -i {
this.tree[i] += v
}
}
func (this *NumArray) prefix(i int) int { // sum of nums[:i]
s := 0
for ; i > 0; i -= i & -i {
s += this.tree[i]
}
return s
}
func (this *NumArray) Update(index int, val int) {
this.add(index+1, val-this.nums[index])
this.nums[index] = val
}
func (this *NumArray) SumRange(left int, right int) int {
return this.prefix(right+1) - this.prefix(left)
}