Range Sum Query

Design a class NumArray that answers range-sum questions about a fixed array:

  • new NumArray(nums) receives the integer array nums. The array never changes afterwards.
  • sumRange(left, right) returns the sum of nums[left], nums[left + 1], …, nums[right]. Both ends are included.

There can be many sumRange calls on the same object, so make each call fast.

Each test is a sequence of calls: the first creates the object (its output is shown as null), and every following call is sumRange with the given arguments.

Constraints

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

Examples

Example 1

Input: ["NumArray","sumRange","sumRange","sumRange"]
       [[[3,-1,4,1,-5,9]],[0,2],[2,5],[0,5]]
Output: [null,6,9,11]

sumRange(0, 2) = 3 + -1 + 4 = 6; sumRange(2, 5) = 4 + 1 + -5 + 9 = 9; the whole array sums to 11. The constructor returns nothing (null).

Example 2

Input: ["NumArray","sumRange"]
       [[[7]],[0,0]]
Output: [null,7]

A single element: the only range is [0, 0].

Example 3

Input: ["NumArray","sumRange","sumRange","sumRange","sumRange"]
       [[[1,2,3,4]],[1,1],[3,3],[0,3],[1,2]]
Output: [null,2,4,10,5]

Ranges are inclusive at both ends, so sumRange(1, 1) is just nums[1] = 2.

Each test creates the class with the first operation, then calls the methods in order. Output lists what each call returns; null marks the constructor and methods that return nothing, and their return values aren't checked.

JavaScript you'll use: Classes for data structures Arrays: create, read, update

class NumArray {
  /**
   * @param {number[]} nums
   */
  constructor(nums) {
    
  }

  /**
   * Sum of nums[left..right], both ends included.
   * @param {number} left
   * @param {number} right
   * @return {number}
   */
  sumRange(left, right) {
    
  }
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.