Range Sum Query – Mutable
Design a data structure over an integer array that supports two operations efficiently: update(index, val) sets the element at index to val, and sumRange(left, right) returns the sum of elements from index left to right inclusive. Both may be called many times interleaved.
Open official problem prompt ↗Support fast range sums on an array whose values keep changing, without paying O(n) for either operation.
Think of nested measuring cups where each cup already holds the total of a run of smaller cups. To read a total you stack a few cups; to change one value you top up only the cups that contain it — never all of them.
- Input
- NumArray([1,3,5]); sumRange(0,2); update(1,2); sumRange(0,2)
- Output
- 9, then 8
- Why
- Initial sum 1+3+5 = 9; after setting index 1 to 2 the array is [1,2,5], so 1+2+5 = 8.
1 <= nums.length <= 3 * 10^4-100 <= nums[i] <= 1000 <= index < nums.length0 <= left <= right < nums.lengthAt most 3 * 10^4 calls to update and sumRange