Range Sum Query - Mutable
1 approach, code in every language
Problem description
Design a structure over an integer array that supports two operations run in any order and any number of times. The first operation overwrites the value stored at a single position. The second operation reports the total of every value that sits between two indices, inclusive of both ends.
Because updates and range totals can be interleaved thousands of times, a naive re-scan on each query is too slow. The goal is to keep both the point update and the inclusive range total fast, so a Fenwick tree (binary indexed tree) that tracks partial sums is a natural fit.
Example 1
Input: ["NumArray","sumRange","update","sumRange"] [[[1,3,5]],[0,2],[1,2],[0,2]]
Output: [null,9,null,8]
Build over [1,3,5]. sumRange(0,2) adds 1+3+5 = 9. update(1,2) turns the array into [1,2,5]. sumRange(0,2) now adds 1+2+5 = 8.
Example 2
Input: ["NumArray","sumRange","update","update","sumRange"] [[[2,4]],[0,1],[0,3],[1,1],[0,1]]
Output: [null,6,null,null,4]
Build over [2,4]. sumRange(0,1) = 6. update(0,3) gives [3,4], update(1,1) gives [3,1], so sumRange(0,1) = 3+1 = 4.
Constraints
1 ≤ nums.length ≤ 3 × 10^4-100 ≤ nums[i] ≤ 1000 ≤ index < nums.length and -100 ≤ val ≤ 1000 ≤ left ≤ right < nums.length, with at most 3 × 10^4 calls to update and sumRange
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free