Skip to content

Practice Range Sum Query - Mutable

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Medium#307
LeetCode Problem

Range Sum Query - Mutable

Problem Statement

NumArray(nums) supports point replacement and inclusive range sums. update(index, val) replaces nums[index] with val. sumRange(left, right) returns the current total from left through right. Practice approach: Use a Fenwick tree or segment tree. For a Fenwick update, retain the previous array value and add val - oldValue to the affected tree nodes; update is replacement, not increment. Range sum is the difference of two prefix sums. Updates and queries take O(log n) with O(n) memory. An immutable prefix array alone becomes stale after updates.

Source: Range Sum Query - Mutable on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["NumArray","sumRange","update","sumRange","sumRange"]
[[[4,-2,7]],[0,2],[1,3],[0,2],[1,1]]
Output
[null,9,null,14,3]
Explanation

Replacing -2 with 3 increases the total by 5. It does not add 3 to the old value.

Constraints

1 <= nums.length <= 3 * 10^4
-100 <= nums[i], val <= 100
0 <= index < nums.length
0 <= left <= right < nums.length
At most 3 * 10^4 total calls to update and sumRange.

Related LeetCode Problems

Practice more problems similar to Range Sum Query - Mutable.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.