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 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
Segment Tree: Range Sum Query15[0-3]4[0-1]11[2-3]1[0]3[1]5[2]6[3]Query: sumRange(1, 2) = 8โšก Tree traversal finds optimal nodes covering range [1,2]๐Ÿ“Š Combines leaf nodes [1] and [2]: 3 + 5 = 8โฐ Time Complexity: O(log n) - only visits log n nodes๐Ÿ”ง Update: Modify leaf and propagate up the treeQuery Range
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
96.5K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen