Answer a Range Sum Query on an Array

Implement rangeSum

Given an array of integers nums, answer queries of the form: what is the sum of the elements between index left and index right, inclusive? Summing the range directly answers one query correctly, but it re-walks the same ground every time. In a system where the array stays fixed and the same range gets queried over and over, that's wasted work — a prefix sumPrefix SumA precomputed running total, where prefix[i] holds the sum of every element before index i. Once built, the sum of any range can be found with a single subtraction instead of re-adding every element in that range. array, built once, turns every future range query into a single subtraction.

Example 1:

Input: nums = [-2,0,3,-5,2,-1], left = 0, right = 2

Output: 1

Example 2:

Input: nums = [-2,0,3,-5,2,-1], left = 2, right = 5

Output: -1

Example 3:

Input: nums = [-2,0,3,-5,2,-1], left = 0, right = 5

Output: -3

+ 8 hidden test cases run on Submit.

Constraints:

  • 1 ≤ nums.length ≤ 10⁴
  • -10⁵ ≤ nums[i] ≤ 10⁵
  • 0 ≤ left ≤ right < nums.length

nums =

[-2, 0, 3, -5, 2, -1]

left =

0

right =

2