Problem
Given an integer array nums, handle multiple queries of the following types:
- Update the value of an element in nums.
- Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
- NumArray(int[] nums) Initializes the object with the integer array nums.
- void update(int index, int val) Updates the value of nums[index] to be val.
- int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + … + nums[right]).
Algorithm
Use a Fenwick Tree (Binary Indexed Tree) to store data and perform sum queries, allowing operations with a time complexity of log(n).
Code
class NumArray:
def _lowbit(self, x: int) -> int:
return x & -x
def _add(self, i: int, delta: int):
while i <= self.nlen:
self.c[i] += delta
i += self._lowbit(i)
def _prefix_sum(self, i: int) -> int:
res = 0
while i > 0:
res += self.c[i]
i -= self._lowbit(i)
return res
def __init__(self, nums: List[int]):
self.nlen = len(nums)
self.nums = nums[:]
self.c = [0] * (self.nlen + 1)
for i in range(self.nlen):
self._add(i + 1, nums[i])
def update(self, index: int, val: int) -> None:
delta = val - self.nums[index]
self.nums[index] = val
self._add(index + 1, delta)
def sumRange(self, left: int, right: int) -> int:
return self._prefix_sum(right + 1) - self._prefix_sum(left)
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# obj.update(index,val)
# param_2 = obj.sumRange(left,right)