design
prefix-sum
fenwick-tree
You are given an initial integer array nums plus three parallel arrays describing operations to perform from left to right.
At index i:
- if
operations[i] == "update", setnums[first[i]] = second[i]; - if
operations[i] == "sumRange", append the sum ofnums[first[i]..second[i]](inclusive) to the answer.
Return the list of outputs produced by all sumRange operations.
Input / output
- Input:
nums: int[],operations: string[],first: int[],second: int[] - Output:
int[]containing every query result in order
Examples
nums = [1,3,5],operations = ["sumRange","update","sumRange"],first = [0,1,0],second = [2,2,2]returns[9,8].nums = [7],operations = ["sumRange","update","sumRange"],first = [0,0,0],second = [0,-1,0]returns[7,-1].nums = [2,4,6,8],operations = ["sumRange","update","sumRange","update","sumRange"],first = [1,2,1,0,0],second = [3,10,3,5,2]returns[18,22,19].
Constraints
1 <= nums.length <= 3 * 10^41 <= operations.length == first.length == second.length <= 3 * 10^4operations[i]is either"update"or"sumRange"0 <= first[i], second[i] < nums.lengthforsumRangeoperations withfirst[i] <= second[i]0 <= first[i] < nums.lengthforupdateoperations
Target complexity
- Aim for
O(log n)per update/query afterO(n log n)or better preprocessing.
Hints
- A prefix-sum array answers queries quickly, but a single update would force many entries to change.
- A Fenwick tree stores partial sums so both point updates and prefix queries stay logarithmic.
Follow-up When would a segment tree be preferable to a Fenwick tree for this family of range-query problems?
Examples
Example 1
Input: nums = [1,3,5], operations = ["sumRange","update","sumRange"], first = [0,1,0], second = [2,2,2]
Output: [9,8]
Example 2
Input: nums = [7], operations = ["sumRange","update","sumRange"], first = [0,0,0], second = [0,-1,0]
Output: [7,-1]
Example 3
Input: nums = [2,4,6,8], operations = ["sumRange","update","sumRange","update","sumRange"], first = [1,2,1,0,0], second = [3,10,3,5,2]
Output: [18,22,19]
🔒 6 hidden
Running will execute all 9 cases, including 6 hidden ones.