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 sumRangeSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI