MediumArrayBinary Indexed TreeSegment TreeDesign

Range Sum Query - Mutable

LeetCode
1 approach, code in all languages

Design a structure over an integer array that supports two operations run in any order and any number of times. The first operation overwrites the value stored at a single position. The second operation reports the total of every value that sits between two indices, inclusive of both ends.

Because updates and range totals can be interleaved thousands of times, a naive re-scan on each query is too slow. The goal is to keep both the point update and the inclusive range total fast, so a Fenwick tree (binary indexed tree) that tracks partial sums is a natural fit.

Example 1

Input: ["NumArray","sumRange","update","sumRange"] [[[1,3,5]],[0,2],[1,2],[0,2]]

Output: [null,9,null,8]

Build over [1,3,5]. sumRange(0,2) adds 1+3+5 = 9. update(1,2) turns the array into [1,2,5]. sumRange(0,2) now adds 1+2+5 = 8.

Example 2

Input: ["NumArray","sumRange","update","update","sumRange"] [[[2,4]],[0,1],[0,3],[1,1],[0,1]]

Output: [null,6,null,null,4]

Build over [2,4]. sumRange(0,1) = 6. update(0,3) gives [3,4], update(1,1) gives [3,1], so sumRange(0,1) = 3+1 = 4.

Constraints

  • 1 ≤ nums.length ≤ 3 × 10^4
  • -100 ≤ nums[i] ≤ 100
  • 0 ≤ index < nums.length and -100 ≤ val ≤ 100
  • 0 ≤ left ≤ right < nums.length, with at most 3 × 10^4 calls to update and sumRange
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now