0303 Range Sum Query#
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 array nums.
int sumRange(int left, int right)
Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + … + nums[right]).
Examples#
Example 1:
Input
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]
Explanation
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
Constraint#
1 <= nums.length <= 104
-105 <= nums[i] <= 105
0 <= left <= right < nums.length
At most 104 calls will be made to sumRange.
Analysis#
we can definitely use
for
loop to do the summation, but it will be inefficient if thesumRange
method will be called thousands of times as each call is \(O(n)\).Here we precalculate the accumalative sum in \(O(n)\), and then can call
sumRange
in \(O(1)\).
Solution#
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)
class NumArray:
def __init__(self, nums: list):
self.nums = nums
self.pre_sums = self.presum()
def presum(self):
pre_sums = [0]
for num in self.nums:
pre_sums.append(pre_sums[-1]+num)
return pre_sums
def sumRange(self, left: int, right: int) -> int:
return self.pre_sums[right+1] - self.pre_sums[left]
# tests
nums = [-2, 0, 3, -5, 2, -1]
array = NumArray(nums)
print(array.sumRange(0, 2))
print(array.sumRange(2, 5))
print(array.sumRange(0, 5))
1
-1
-3