#307
Range Sum Query - Mutable
MediumArrayDivide and ConquerDesignBinary Indexed TreeSegment TreeSegment TreesBinary Indexed Trees
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(log n)Space O(n)
Using a Segment Tree allows us to efficiently update elements and calculate range sums in logarithmic time. This is crucial for handling many queries quickly.
⚙️
Algorithm
3 steps- 1Step 1: Build a Segment Tree from the input array, where each node represents the sum of a segment of the array.
- 2Step 2: For the update operation, update the specific index in the Segment Tree, which takes O(log n) time.
- 3Step 3: For the sumRange operation, query the Segment Tree to get the sum of the specified range, also in O(log n) time.
solution.py40 lines
1class SegmentTree:
2 def __init__(self, nums):
3 self.n = len(nums)
4 self.tree = [0] * (2 * self.n)
5 for i in range(self.n):
6 self.tree[self.n + i] = nums[i]
7 for i in range(self.n - 1, 0, -1):
8 self.tree[i] = self.tree[i * 2] + self.tree[i * 2 + 1]
9
10 def update(self, index, val):
11 index += self.n
12 self.tree[index] = val
13 while index > 1:
14 index //= 2
15 self.tree[index] = self.tree[index * 2] + self.tree[index * 2 + 1]
16
17 def sumRange(self, left, right):
18 left += self.n
19 right += self.n + 1
20 sum_ = 0
21 while left < right:
22 if left % 2:
23 sum_ += self.tree[left]
24 left += 1
25 if right % 2:
26 right -= 1
27 sum_ += self.tree[right]
28 left //= 2
29 right //= 2
30 return sum_
31
32class NumArray:
33 def __init__(self, nums):
34 self.segment_tree = SegmentTree(nums)
35
36 def update(self, index, val):
37 self.segment_tree.update(index, val)
38
39 def sumRange(self, left, right):
40 return self.segment_tree.sumRange(left, right)ℹ
Complexity note: The time complexity is O(log n) for both update and sumRange operations due to the properties of the Segment Tree, which allows us to efficiently manage updates and queries on the array.
- 1Understanding the difference between direct iteration and more complex data structures like Segment Trees is crucial for optimizing performance.
- 2Recognizing when to use a data structure based on the types of operations required (updates vs. queries) can greatly enhance efficiency.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.