Example 1
- Input
- NumArray([1,3,5]); sumRange(0,2); update(1,2); sumRange(0,2)
- Output
- [null,9,null,8]
Construction and assignment return null in the operation transcript. The first sum is 9; replacing 3 by 2 makes the next sum 8.
Support point assignments and inclusive range sums on an integer array. Compare direct scanning, a Segment Tree and a Fenwick Tree.
Implement NumArray(nums), update(index, val) and sumRange(left, right). An update replaces one value; it does not add val to that value. A query returns the sum from left through right inclusive, using zero-based indices. The official exercise interleaves updates and queries on the same object.
1 <= nums.length <= 3 × 10^4.-100 <= nums[i], val <= 100.0 <= index < nums.length; 0 <= left <= right < nums.length.3 × 10^4 calls to update and sumRange.Construction and assignment return null in the operation transcript. The first sum is 9; replacing 3 by 2 makes the next sum 8.
A singleton inclusive range contains that one value. Assigning zero applies delta +5.
Assigning the same value has delta zero. The partial sum is -1+4=3; replacing 4 with -4 changes the full sum to 2-1-4=-3.
A direct scan repeats work when queries overlap. Store sums of reusable blocks so an update repairs only the blocks containing its index. Example 1 changes 3 to 2, a delta of -1, so the full sum changes from 9 to 8. A Segment Tree combines child sums; a Fenwick Tree organizes prefix blocks with the lowest set bit. Fenwick is selected for this sum-only interface because it needs one compact tree array; Segment Trees generalize to more operations.
Reveal Direct Scan: intuition, complexity, and code
Mutable aggregates need a representation that limits repair after a point change. Prefix subtraction requires an inverse operation; a Segment Tree can combine blocks even when subtraction is unavailable.