Range Sum Query - Mutable – Solution & Complexity
Solution Walkthrough
Step 1: Why a plain prefix array is not enough
- With no updates, prefix sums answer every range query in
O(1). - But after setting one position to a new value, every prefix sum after that index changes, so a plain prefix array makes updates
O(n).
- With no updates, prefix sums answer every range query in
Step 2: Brute-force baseline
- You can perform updates directly in
numsand answer eachsumRangeby looping fromlefttoright. - That costs
O(n)per query and is too slow when both the array and the operation list are large.
- You can perform updates directly in
Step 3: Store partial sums in a Fenwick tree
- A Fenwick tree stores carefully chosen prefix fragments so one point update touches only
O(log n)tree slots. - A prefix query also touches only
O(log n)slots, and an inclusive range sum becomesprefix(right) - prefix(left - 1). - Keep a copy of
numsso you can compute the delta when an update overwrites an old value.
- A Fenwick tree stores carefully chosen prefix fragments so one point update touches only
Step 4: Final solution (all languages)
Fenwick-tree partial sums give logarithmic updates and queries with compact code.
Step 5: Implementation notes
- The Fenwick tree uses 1-based indexing internally even though the problem uses 0-based array indices.
updateoverwrites a value, so you must add the difference (new - old) instead of the new value itself.- A segment tree solves the same interface and extends more naturally to range updates or different associative operations.