Range Sum Query - Immutable
1 approach, code in every language
Problem description
Design a data structure that, given a fixed integer array nums, can answer many range-sum queries efficiently.
Implement a class NumArray that is constructed from nums and supports the operation sumRange(left, right), which returns the sum of the elements between indices left and right inclusive, that is nums[left] + nums[left + 1] + ... + nums[right]. The array never changes after construction, so queries should not require re-scanning the elements each time.
Example 1
Input: NumArray([-2,0,3,-5,2,-1]); sumRange(0,2); sumRange(2,5); sumRange(0,5)
Output: 1, -1, -3
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
Input: NumArray([1,2,3,4]); sumRange(1,3); sumRange(0,0)
Output: 9, 1
sumRange(1,3) = 2 + 3 + 4 = 9 and sumRange(0,0) = 1.
Constraints
1 <= nums.length <= 10^4-10^5 <= nums[i] <= 10^50 <= left <= right < nums.lengthAt most 10^4 calls will be made to sumRange.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free