Design a data structure that, given a fixed integer array nums, can answer many range-sum queries efficiently.
Implement a class NumArray that is constructed from nums and supports the operation sumRange(left, right), which returns the sum of the elements between indices left and right inclusive, that is nums[left] + nums[left + 1] + ... + nums[right]. The array never changes after construction, so queries should not require re-scanning the elements each time.
Example 1
Input: NumArray([-2,0,3,-5,2,-1]); sumRange(0,2); sumRange(2,5); sumRange(0,5)
Output: 1, -1, -3
sumRange(0,2) = -2 + 0 + 3 = 1, sumRange(2,5) = 3 - 5 + 2 - 1 = -1, sumRange(0,5) = -2 + 0 + 3 - 5 + 2 - 1 = -3.
Example 2
Input: NumArray([1,2,3,4]); sumRange(1,3); sumRange(0,0)
Output: 9, 1
sumRange(1,3) = 2 + 3 + 4 = 9 and sumRange(0,0) = 1.
Constraints
1 <= nums.length <= 10^4-10^5 <= nums[i] <= 10^50 <= left <= right < nums.lengthAt most 10^4 calls will be made to sumRange.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI