Range Sum Query - Mutable Problem
#307
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 307.
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
numsbetween indicesleftandrightinclusive whereleft <= right.
Implement the NumArray class:
NumArray(int[] nums)Initializes the object with the integer arraynums.void update(int index, int val)Updates the value ofnums[index]to beval.int sumRange(int left, int right)Returns the sum of the elements ofnumsbetween indicesleftandrightinclusive (i.e.nums[left] + nums[left + 1] + ... + nums[right]).
Example 1:
Input
["NumArray", "sumRange", "update", "sumRange"]
[[[1, 3, 5]], [0, 2], [1, 2], [0, 2]]
Output
[null, 9, null, 8]
Explanation
NumArray numArray = new NumArray([1, 3, 5]);
numArray.sumRange(0, 2); // return 1 + 3 + 5 = 9
numArray.update(1, 2); // nums = [1, 2, 5]
numArray.sumRange(0, 2); // return 1 + 2 + 5 = 8
Constraints:
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 1000 <= index < nums.length-100 <= val <= 1000 <= left <= right < nums.length- At most
3 * 10^4calls will be made toupdateandsumRange.
Solution
Approach: Binary Indexed Tree (Fenwick Tree)
A plain array makes update O(1) but sumRange O(n); a prefix-sum array does the opposite, because one update changes every prefix after it. With up to 3 * 104 calls of each kind we want both in O(log n).
A binary indexed tree does exactly that. It is an array tree[1..n] where tree[i] holds the sum of nums over a block that ends at position i and has length i & -i (the lowest set bit of i). Two operations walk these blocks:
- add(i, delta): add
deltato positioni. Every block that containsichanges; we visit them withi += i & -i. - prefix(i): the sum of the first
ivalues. The blocks ending ati,i - (i & -i), ... cover positions1..iexactly once; we visit them withi -= i & -i.
Both loops run at most log n times. Then:
- The constructor calls
add(i + 1, nums[i])for every index (the tree is 1-indexed). update(index, val)cannot writevalinto the tree directly, because the tree only stores sums. It adds the differenceval - nums[index], so we keep a copy ofnumsto know the old value.sumRange(left, right)isprefix(right + 1) - prefix(left).
Complexity: O(n log n) to build, O(log n) per update and sumRange, and O(n) extra space.
class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums[:]
self.n = len(nums)
self.tree = [0] * (self.n + 1) # Fenwick tree, 1-indexed
for i, x in enumerate(nums):
self._add(i + 1, x)
def _add(self, i: int, delta: int) -> None:
while i <= self.n:
self.tree[i] += delta
i += i & -i
def _prefix(self, i: int) -> int: # nums[0] + ... + nums[i - 1]
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def update(self, index: int, val: int) -> None:
self._add(index + 1, val - self.nums[index]) # the tree only stores sums, so add the difference
self.nums[index] = val
def sumRange(self, left: int, right: int) -> int:
return self._prefix(right + 1) - self._prefix(left)