Range Sum Query - Mutable - Problem
Range Sum Query - Mutable challenges you to build an efficient data structure that handles two critical operations on an array: updates and range sum queries.
You're given an integer array
• Update Operation: Change the value at any index
• Range Sum Query: Calculate the sum of elements between any two indices (inclusive)
The key challenge is handling multiple operations efficiently. A naive approach might recalculate sums from scratch each time, but with potentially thousands of operations, you need something faster.
Example:
You're given an integer array
nums and need to implement the NumArray class that supports:• Update Operation: Change the value at any index
• Range Sum Query: Calculate the sum of elements between any two indices (inclusive)
The key challenge is handling multiple operations efficiently. A naive approach might recalculate sums from scratch each time, but with potentially thousands of operations, you need something faster.
Example:
NumArray numArray = new NumArray([1, 3, 5]);numArray.sumRange(0, 2); // Returns 9 (1+3+5)numArray.update(1, 2); // Array becomes [1, 2, 5]numArray.sumRange(0, 2); // Returns 8 (1+2+5) Input & Output
example_1.py — Basic Operations
$
Input:
NumArray([1, 3, 5])
sumRange(0, 2)
update(1, 2)
sumRange(0, 2)
›
Output:
9
8
💡 Note:
Initial array [1,3,5] has sum 9 for range [0,2]. After updating index 1 to value 2, array becomes [1,2,5] with sum 8.
example_2.py — Single Element
$
Input:
NumArray([7])
sumRange(0, 0)
update(0, 3)
sumRange(0, 0)
›
Output:
7
3
💡 Note:
Single element array: sum of range [0,0] is just the element itself. After update, the value changes from 7 to 3.
example_3.py — Multiple Updates
$
Input:
NumArray([1, 2, 3, 4, 5])
sumRange(0, 4)
update(2, 10)
sumRange(0, 4)
update(4, 1)
sumRange(0, 4)
›
Output:
15
22
18
💡 Note:
Original sum: 1+2+3+4+5=15. After update(2,10): 1+2+10+4+5=22. After update(4,1): 1+2+10+4+1=18.
Constraints
- 1 ≤ nums.length ≤ 3 × 104
- -100 ≤ nums[i] ≤ 100
- 0 ≤ index < nums.length
- -100 ≤ val ≤ 100
- 0 ≤ left ≤ right < nums.length
- At most 3 × 104 calls will be made to update and sumRange
Visualization
Tap to expand
Understanding the Visualization
1
Build Tree Structure
Create binary tree with each node storing sum of its range
2
Handle Range Query
Traverse tree to find nodes that cover the query range optimally
3
Process Update
Modify leaf node and propagate changes up to maintain tree properties
Key Takeaway
🎯 Key Insight: Segment Trees achieve optimal O(log n) performance by hierarchically organizing range information, making both updates and queries logarithmic in the array size.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code