Range Queries Fenwick tree
607. Range Sum Query - Mutable
You are given an integer array nums. Write a class NumArray that keeps the array and handles two kinds of
calls, in any order:
NumArray(nums)stores the array.update(index, val)setsnums[index]toval. The new value replaces the old one.sumRange(left, right)returns the sum of the elements from indexleftto indexright, both ends included, as the array is at the time of the call.
Indices start at 0. Every sum must see every update made before it.
Your class is tested by replaying a list of calls on a new NumArray(nums). ops[i] names the i-th call,
"update" or "sumRange", and args[i] holds its two arguments: [index, val] for an update and
[left, right] for a sum. The answer is the list of every value that sumRange returns, in the order of the
calls.
In C# and Go the methods are Update and SumRange, and in Rust sum_range. Go creates the object with
Constructor(nums), and Rust with NumArray::new(nums). The names in ops are the same in every language.
Example 1
Input: nums = [4, -1, 7, 2, -3]
ops = ["sumRange",
"update",
"sumRange",
"sumRange",
"update",
"sumRange"]
args = [[0, 2],
[1, 5],
[0, 2],
[1, 3],
[4, 10],
[2, 4]]
[10,16,14,19]Explanation: The first sum adds 4, −1 and 7. update(1, 5) turns the −1 into 5, so the same range now gives 16, and
indices 1 to 3 give 5 + 7 + 2 = 14. After update(4, 10), indices 2 to 4 give 7 + 2 + 10 = 19.
Example 2
Input: nums = [-5, 0, 3]
ops = ["update",
"update",
"sumRange",
"sumRange"]
args = [[0, 8], [0, -2], [0, 0], [0, 2]]
[-2,1]Explanation: Each update replaces the value at index 0, so after both of them the array is [-2,0,3]. The 8 is gone,
and the −5 never adds to anything.
Example 3
Input: nums = [1000000000, 1000000000, -1000000000]
ops = ["sumRange", "update", "sumRange"]
args = [[0, 1], [2, 1000000000], [0, 2]]
[2000000000,3000000000]Explanation: After the update every element is 109, and the second sum is 3 × 109, more than a 32-bit integer can hold.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ ops.length ≤ 105, soupdateandsumRangeare called at most 105 times in all.- Each
ops[i]is"update"or"sumRange". args.lengthequalsops.length.- For an update,
args[i] = [index, val]with0 ≤ index < nums.lengthand-109 ≤ val ≤ 109. - For a sum,
args[i] = [left, right]with0 ≤ left ≤ right < nums.length.
Clarifying questions
What you would ask an interviewer before writing any code.