medium

Range Sum Query — Mutable

Design a structure over an integer array supporting two interleaved operations: update(i, v) sets element i to v, and sumRange(l, r) returns the sum of elements from l to r inclusive. Both must be fast for large numbers of calls.

Constraints
  • 1 ≤ n ≤ 3 · 10^4
  • -100 ≤ nums[i] ≤ 100
  • At most 3 · 10^4 calls to update and sumRange
Examples
in: nums = [1,3,5]; sumRange(0,2), update(1,2), sumRange(0,2)
out: 9, 8
Recognition clues
  • Point updates interleaved with range queries
  • Plain prefix sums cost O(n) per update
  • Balanced tree of partial sums — O(log n) each
Pattern
Segment / Fenwick Tree

Prefix sums break the moment the array changes, since every prefix after the update shifts. A Fenwick or segment tree stores partial aggregates over power-of-two ranges so both a point update and a range query touch only O(log n) nodes. Use a sparse table instead when the array is static and the operation is idempotent (min, max, gcd).

Solution

Build a segment tree where each node stores the sum of a contiguous range and leaves are individual elements. update changes a leaf and recomputes the sums along the path to the root. sumRange descends from the root, returning a node's sum when its range lies inside the query, ignoring nodes outside it and recursing into partially overlapping ones — at most O(log n) nodes are combined.

time O(log n) per operation, O(n) buildspace O(n)
Alternative approaches
  • A Fenwick tree does the same with less code and memory using prefix sums and the lowest-set-bit trick. Sqrt decomposition gives O(√n) operations with the simplest code.
Code it yourself
Solve in
Hints:
Learn Segment Tree▶ Visualize