Design a data structure that supports point updates and range-sum queries on an array.
Mutable Range Sum Query
gfgProblem
You are given an integer array that changes over time. Build a data structure that can:
- Update the value at a single index.
- Query the sum of values within any inclusive subarray range.
After each update, future queries must reflect the new values.
Your goal is to support both operations efficiently, rather than recomputing sums from scratch each time.
Input Format
- An initial integer array
nums. - A sequence of operations of two types:
update(index, val): setnums[index] = valsumRange(left, right): return the sum ofnums[left..right]inclusive
Output Format
- For each range-sum query, return the computed sum as an integer.
Constraints
- The array length and number of operations can be large enough that naive re-summing after every update is too slow.
- Indices are zero-based.
- Range queries are inclusive.
Example 1
Input
nums = [1, 3, 5] update(1, 2) sumRange(0, 2) sumRange(1, 2)
Output
[8, 7]
Explanation
After the update, the array becomes [1, 2, 5]. The sum of the full range is 8, and the sum of the last two elements is 7.
Example 2
Input
nums = [0, -1, 4, 2] sumRange(1, 3) update(2, 10) sumRange(0, 2)
Output
[5, 9]
Explanation
The first query returns -1 + 4 + 2 = 5. After updating index 2, the array becomes [0, -1, 10, 2], so the second query returns 0 + (-1) + 10 = 9.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.