Skip to content
Onsite

Range Sum Query - Immutable

EasyP2Coding

Design a class that answers range-sum queries on a fixed array.

Implement NumArray:

  • NumArray(nums) stores the array nums.
  • sumRange(left, right) returns the sum of nums[left] through nums[right], both inclusive.

The array never changes, and there may be many queries, so each sumRange call should run in O(1).

Example 1

Input
["NumArray","sumRange","sumRange","sumRange"] [[[-2,0,3,-5,2,-1]],[0,2],[2,5],[0,5]]
Output
[null,1,-1,-3]
Why
The sums are -2+0+3 = 1, 3-5+2-1 = -1, and the whole array = -3.

Constraints

  • 1 <= nums.length <= 10^4
  • -10^5 <= nums[i] <= 10^5
  • 0 <= left <= right < nums.length
  • At most 10^4 calls to sumRange.

Hints

Run checks the 3 visible tests, Submit all 8.