Build a class that gets an array of numbers once and then answers many queries: the sum of the numbers from index left to index right, both included. The array never changes. Our example: [4, -2, 3, 5, -1, 2] and three queries — sumRange(2, 4) = 7, sumRange(0, 3) = 10 and sumRange(1, 1) = -2.
input
Calls one after another: NumArray(nums) gets the array once, then each sumRange(left, right) asks about a part of it. The array never changes.
returns
sumRange(left, right) returns the sum of nums[left] to nums[right], both included.
constraints
1 ≤ calls of sumRange ≤ 2000
1 ≤ nums.length ≤ 2000
−10⁵ ≤ nums[i] ≤ 10⁵
0 ≤ left ≤ right < nums.length
our 10 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
timer
switch language →
/**
* @param {number[]} nums
*/
var NumArray = function(nums) {
};
/**
* @param {number} left
* @param {number} right
* @return {number}
*/
NumArray.prototype.sumRange = function(left, right) {
};
/**
* Your NumArray object will be instantiated and called as such:
* var obj = new NumArray(nums)
* var param_1 = obj.sumRange(left, right)
*/
Ctrl ↵
format
reset
saved in this browser
10 tests · limit 3 s
Stuck?
See the solution run step by step on our example, then why it works and its complexity.