Range Sum Query - Mutable (LeetCode 307): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Store
nand allocatetree = [0] * (2 * n). - Copy
nums[i]intotree[n + i], then fill internal nodes fromn - 1down to 1 withtree[2i] + tree[2i + 1]. - For
update(index, val), set the leaftree[index + n]and walk up, recomputing each parent as the sum of its two children until reaching the root. - For
sumRange(left, right), shift both bounds to leaf positions and starttotal = 0. - While
left <= right: ifleftis odd, addtree[left]and increment it; ifrightis even, addtree[right]and decrement it; then halve both. - Return
total.
Step-by-step example
nums = [1, 3, 5], sumRange(0, 2), update(1, 2), sumRange(0, 2)
- Leaves go to indices 3, 4, 5, so
tree = [0, _, _, 1, 3, 5]. Thentree[2] = 3 + 5 = 8andtree[1] = 8 + 1 = 9. sumRange(0, 2)starts withleft = 3,right = 5.leftis odd, so addtree[3] = 1and move to 4.rightis odd, so skip. Halving givesleft = 2,right = 2.- Now
right = 2is even, so addtree[2] = 8for a total of 9, and the bounds cross. The answer is 9. update(1, 2)setstree[4] = 2, thentree[2] = 2 + 5 = 7andtree[1] = 7 + 1 = 8.- Running the same query again adds
tree[3] = 1andtree[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 total1class NumArray {
2 private int n;
3 private int[] tree;
4
5 public NumArray(int[] nums) {
6 n = nums.length;
7 tree = new int[2 * n];
8 for (int i = 0; i < n; i++) {
9 tree[n + i] = nums[i];
10 }
11 for (int i = n - 1; i > 0; i--) {
12 tree[i] = tree[2 * i] + tree[2 * i + 1];
13 }
14 }
15
16 public void update(int index, int val) {
17 index += n;
18 tree[index] = val;
19 while (index > 1) {
20 index /= 2;
21 tree[index] = tree[2 * index] + tree[2 * index + 1];
22 }
23 }
24
25 public int sumRange(int left, int right) {
26 left += n;
27 right += n;
28 int total = 0;
29 while (left <= right) {
30 if (left % 2 == 1) { total += tree[left]; left++; }
31 if (right % 2 == 0) { total += tree[right]; right--; }
32 left /= 2;
33 right /= 2;
34 }
35 return total;
36 }
37}1class NumArray {
2 int n;
3 vector<int> tree;
4public:
5 NumArray(vector<int>& nums) {
6 n = nums.size();
7 tree.resize(2 * n);
8 for (int i = 0; i < n; i++) {
9 tree[n + i] = nums[i];
10 }
11 for (int i = n - 1; i > 0; i--) {
12 tree[i] = tree[2 * i] + tree[2 * i + 1];
13 }
14 }
15
16 void update(int index, int val) {
17 index += n;
18 tree[index] = val;
19 while (index > 1) {
20 index /= 2;
21 tree[index] = tree[2 * index] + tree[2 * index + 1];
22 }
23 }
24
25 int sumRange(int left, int right) {
26 left += n;
27 right += n;
28 int total = 0;
29 while (left <= right) {
30 if (left % 2 == 1) { total += tree[left]; left++; }
31 if (right % 2 == 0) { total += tree[right]; right--; }
32 left /= 2;
33 right /= 2;
34 }
35 return total;
36 }
37};Time and space complexity
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.
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
2nwithout padding. Recursive trees need about4nslots; the2nlayout 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
nbefore walking, so the query starts on internal nodes instead of leaves. - In a Fenwick variant, adding
valinstead ofval - 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).