Range Sum Query - Immutable

EasyArrays & Hashingprefix sum

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given an integer array once, and then asked many questions of the form "what is the sum of the elements from index left to index right, inclusive?" The array never changes. Implement: - NumArray(nums) receives the array. - sumRange(left, right) returns nums[left] + nums[left + 1] + ... + nums[right]. Indices are 0-based and always satisfy 0 <= left <= right < nums.length. Preprocess in O(n) so every query runs in O(1).

Examples

Input: ["NumArray","sumRange","sumRange","sumRange","sumRange"] [[[3,-1,4,-2,6]],[0,2],[1,3],[4,4],[0,4]]
Output: [null,6,1,6,10]
3 + (-1) + 4 = 6; (-1) + 4 + (-2) = 1; the single element at index 4 is 6; the whole array sums to 10.
Input: ["NumArray","sumRange","sumRange"] [[[0,0,7]],[0,1],[2,2]]
Output: [null,0,7]
The first two elements sum to 0 and index 2 alone is 7.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More prefix sum problems