Range Sum Query - Immutable - Problem
Given an integer array nums, handle multiple queries of the following type:
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
NumArray(int[] nums)Initializes the object with the integer arraynums.int sumRange(int left, int right)Returns the sum of the elements ofnumsbetween indicesleftandrightinclusive.
Input & Output
Example 1 — Basic Range Queries
$
Input:
nums = [-2,0,3,-5,2,-1], operations = [["sumRange",0,2],["sumRange",2,5],["sumRange",0,5]]
›
Output:
[1,-1,-3]
💡 Note:
sumRange(0,2) = (-2) + 0 + 3 = 1, sumRange(2,5) = 3 + (-5) + 2 + (-1) = -1, sumRange(0,5) = (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
Example 2 — Single Element Range
$
Input:
nums = [1,3,5], operations = [["sumRange",1,1],["sumRange",0,2]]
›
Output:
[3,9]
💡 Note:
sumRange(1,1) = nums[1] = 3, sumRange(0,2) = 1 + 3 + 5 = 9
Example 3 — Full Array Range
$
Input:
nums = [5,-3,5], operations = [["sumRange",0,0],["sumRange",1,2],["sumRange",0,2]]
›
Output:
[5,2,7]
💡 Note:
sumRange(0,0) = 5, sumRange(1,2) = -3 + 5 = 2, sumRange(0,2) = 5 + (-3) + 5 = 7
Constraints
- 1 ≤ nums.length ≤ 104
- -105 ≤ nums[i] ≤ 105
- 0 ≤ left ≤ right < nums.length
- At most 104 calls to sumRange
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array nums and multiple sumRange queries
2
Process
Build prefix sum array once, then use formula for each query
3
Output
Array of sum results for each query
Key Takeaway
🎯 Key Insight: Precompute prefix sums once to answer any range query in constant time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code