Skip to content
Decoder

Range Sum Query (Immutable)

Easy

Problem

Build a class NumArray that is created from a list of integers nums and then answers many queries. Each query sum_range(left, right) (sumRange in TypeScript) returns the sum of nums[left] through nums[right], inclusive. The list never changes after construction.

Example 1

arr = NumArray([-2, 0, 3, -5, 2, -1])

Example 2

Input
arr.sum_range(0, 2)
Output
1
Why
-2 + 0 + 3

Example 3

Input
arr.sum_range(2, 5)
Output
-1
Why
3 - 5 + 2 - 1

Example 4

Input
arr.sum_range(0, 5)
Output
-3

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.