Range Sum Query - Mutable

Medium Advanced data structures and strings

NumArray(nums) keeps a list of whole numbers, nums, with its places counted from 0.

update(index, val) changes the number at place index to val.

sumRange(left, right) returns the sum of the numbers from place left to place right, both included, in the list as every update so far has left it.

Example 1

Calls:
NumArray([4,-2,7,0,3])
sumRange(0, 2) → 9
update(1, 5)
sumRange(0, 2) → 16
sumRange(1, 4) → 15

Places 0 to 2 hold 4, -2 and 7, which sum to 9. The update makes the list 4, 5, 7, 0, 3: the same places now sum to 16, and places 1 to 4 to 5 + 7 + 0 + 3 = 15.

Example 2

Calls:
NumArray([6])
sumRange(0, 0) → 6
update(0, -6)
sumRange(0, 0) → -6

Example 3

Calls:
NumArray([2,2,2,2])
update(3, 10)
update(0, -1)
sumRange(1, 3) → 14
sumRange(0, 0) → -1
update(3, 2)
sumRange(0, 3) → 5

Constraints

  • 1 ≤ nums.length ≤ 5 × 10⁵
  • -4000 ≤ nums[i] ≤ 4000 and -4000 ≤ val ≤ 4000, so every sum is at most 2 × 10⁹ either side of 0 and fits in a 32-bit int
  • 0 ≤ index < nums.length and 0 ≤ left ≤ right < nums.length
  • at most 10⁵ calls in all to update and sumRange

Practice this in an AI round

30 minutes on this problem with an AI agent beside your code, then a report on your solution and how you used the agent.

See the AI round

More Advanced data structures and strings

All Advanced data structures and strings problems