EasyArrayDesignPrefix Sum

Range Sum Query - Immutable

LeetCode
1 approach, code in all languages

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^5
  • 0 <= left <= right < nums.length
  • At most 10^4 calls will be made to sumRange.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now