Range Sum Query - Mutable (LeetCode 307): Solution and Explanation

Medium
Array
Design
Binary Indexed Tree
Segment Tree

Design a class over an integer array that supports two operations: change the value at one index, and return the sum of a contiguous range. Many of both operations arrive in any order, so neither may be slow.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Two simple designs each fail in one direction. Keeping the raw array makes updates O(1) but every range sum O(n). Keeping prefix sums makes range sums O(1) but every update O(n), since all later prefixes change. With tens of thousands of mixed calls, either one is quadratic.

A segment tree balances the two. It stores sums of power-of-two blocks arranged in a binary tree, so any range can be assembled from O(log n) precomputed blocks, and changing one element only invalidates the O(log n) blocks that contain it.

The reference code uses the compact iterative version. It allocates an array of size 2n, puts the original values in the leaves at indices n through 2n - 1, and stores at each internal index i the sum of its children 2i and 2i + 1. Updating a leaf means walking up with index //= 2 and recomputing each parent. Querying walks the two boundaries upward together. Whenever the left boundary is a right child (odd index), its node will not be covered by its parent's block, so add it and step right. Whenever the right boundary is a left child (even index), add it and step left. Then both move up a level.

Approach: Iterative segment tree

  1. Store n and allocate tree = [0] * (2 * n).
  2. Copy nums[i] into tree[n + i], then fill internal nodes from n - 1 down to 1 with tree[2i] + tree[2i + 1].
  3. For update(index, val), set the leaf tree[index + n] and walk up, recomputing each parent as the sum of its two children until reaching the root.
  4. For sumRange(left, right), shift both bounds to leaf positions and start total = 0.
  5. While left <= right: if left is odd, add tree[left] and increment it; if right is even, add tree[right] and decrement it; then halve both.
  6. Return total.

Step-by-step example

nums = [1, 3, 5], sumRange(0, 2), update(1, 2), sumRange(0, 2)
  1. Leaves go to indices 3, 4, 5, so tree = [0, _, _, 1, 3, 5]. Then tree[2] = 3 + 5 = 8 and tree[1] = 8 + 1 = 9.
  2. sumRange(0, 2) starts with left = 3, right = 5. left is odd, so add tree[3] = 1 and move to 4. right is odd, so skip. Halving gives left = 2, right = 2.
  3. Now right = 2 is even, so add tree[2] = 8 for a total of 9, and the bounds cross. The answer is 9.
  4. update(1, 2) sets tree[4] = 2, then tree[2] = 2 + 5 = 7 and tree[1] = 7 + 1 = 8.
  5. Running the same query again adds tree[3] = 1 and tree[2] = 7, returning 8, which is 1 + 2 + 5.

Code: Python, Java, C++

1class NumArray:
2    def __init__(self, nums: List[int]):
3        self.n = len(nums)
4        self.tree = [0] * (2 * self.n)
5        # Build tree
6        for i in range(self.n):
7            self.tree[self.n + i] = nums[i]
8        for i in range(self.n - 1, 0, -1):
9            self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
10
11    def update(self, index: int, val: int) -> None:
12        index += self.n
13        self.tree[index] = val
14        while index > 1:
15            index //= 2
16            self.tree[index] = self.tree[2 * index] + self.tree[2 * index + 1]
17
18    def sumRange(self, left: int, right: int) -> int:
19        left += self.n
20        right += self.n
21        total = 0
22        while left <= right:
23            if left % 2 == 1:
24                total += self.tree[left]
25                left += 1
26            if right % 2 == 0:
27                total += self.tree[right]
28                right -= 1
29            left //= 2
30            right //= 2
31        return total

Time and space complexity

Time

O(n) build, O(log n) per operation

Building visits each of the 2n slots once. An update walks from a leaf to the root, and a query moves both boundaries up one level per iteration, so each touches O(log n) nodes.

Space

O(n)

The tree array has exactly 2n entries.

Other approaches

Fenwick tree (time O(log n) per operation, space O(n))

A binary indexed tree stores partial sums keyed by the lowest set bit of each index. Update adds the difference, and a range sum is two prefix queries. It is shorter than a segment tree with the same bounds.

Square root decomposition (time O(1) update, O(√n) query, space O(√n) extra)

Split the array into blocks of size about the square root of n and keep each block's sum. Updates fix one block sum, and queries combine partial blocks at the ends with whole blocks in between.

Common mistakes

  • Using the recursive segment tree size of 2n without padding. Recursive trees need about 4n slots; the 2n layout only works with this iterative indexing.
  • Swapping the parity checks in the query. The left boundary is added when it is odd and the right boundary when it is even; reversing them double counts or misses nodes.
  • Forgetting to shift indices by n before walking, so the query starts on internal nodes instead of leaves.
  • In a Fenwick variant, adding val instead of val - nums[index] on update, which accumulates old values.

Frequently asked questions

Why use a segment tree for range sum query mutable?

It supports both point updates and range sums in O(log n), while prefix sums make updates O(n) and a raw array makes queries O(n).

Segment tree or Fenwick tree for this problem?

Both give O(log n) operations. A Fenwick tree is shorter to write, while a segment tree generalizes better to min, max or lazy range updates.

How does the iterative segment tree query work?

It moves the left and right boundaries up the tree together. A boundary node whose parent would include elements outside the range is added on its own, and the walk continues until the boundaries cross.

What is the time complexity of each operation?

Updates and range queries are both O(log n), and building the tree is O(n).