Range Sum Query - Immutable

Given an integer array nums, answer many queries of the form: what is the sum of nums[left] through nums[right], inclusive? Implement NumArray with a constructor NumArray(nums) and a method sumRange(left, right). The array never changes after construction.

30:00

Range Sum Query - Immutable
easy
Free written solution
Topics
Companies

Given an integer array nums, answer many queries of the form: what is the sum of nums[left] through nums[right], inclusive? Implement NumArray with a constructor NumArray(nums) and a method sumRange(left, right). The array never changes after construction.

Example 1:
Input: {"commands":["NumArray","sumRange","sumRange","sumRange"],"values":[[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]}
Output: [null,1,-1,-3]
Constraints:
  • 1≤nums.length≤1041 \leq \text{nums.length} \leq 10^4

  • −105≤nums[i]≤105-10^5 \leq \text{nums[i]} \leq 10^5

  • 0≤left≤right<nums.length0 \leq \text{left} \leq \text{right} < \text{nums.length}

  • At most 10410^4 calls will be made to sumRange.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"commands":["NumArray","sumRange","sumRange","sumRange"],"values":[[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]}

Construct NumArray with 6 numbers. Start the prefix array with a single 0, the sum of no elements.

constructor building 0/6
sumRange calls 0/3

0

-2

1

0

2

3

3

-5

4

2

5

-1
0

p0

?

p1

?

p2

?

p3

?

p4

?

p5

?

p6

0p0p6
being added to prefix
queried range
p[right+1]
p[left]
p[k] is the sum of the first k numbers, so a range sum is the rise of the curve between two posts.
Variables
VariableValue
n6
prefix_len1
DepthFunction Call
Stack empty
0/14