Range Sum Query - Immutable

Easy

Topics
ArrayPrefix SumDesign

Given an integer array nums, handle multiple queries of the sum of the elements between indices left and right inclusive. Implement NumArray(nums) and sumRange(left, right) which returns the sum nums[left] + ... + nums[right].

Example 1

NumArray(-2, 0, 3, -5, 2, -1)sumRange(0, 2)sumRange(2, 5)sumRange(0, 5)
The array never changes, so the work belongs in the constructor. If updates were allowed this would need a Fenwick or segment tree instead.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["NumArray","sumRange","sumRange","sumRange"], values = [[-2,0,3,-5,2,-1],[0,2],[2,5],[0,5]]
Output: [null,1,-1,-3]

Constraints

  • 1 <= nums.length <= 10^4
  • -10^5 <= nums[i] <= 10^5
  • 0 <= left <= right < nums.length
  • At most 10^4 calls to sumRange.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Recomputing a range sum each query is O(n). Precompute a prefix-sum array once so any range sum becomes a single subtraction.

Approach

  1. Build prefix[i] = sum of the first i elements in the constructor.
  2. sumRange(left, right) returns prefix[right + 1] - prefix[left].
  3. Every query is then O(1).

Dry Run

nums   = [-2,  0,  3, -5,  2, -1]
prefix = [ 0, -2, -2,  1, -4, -2, -3]
prefix[i] is the sum of the FIRST i values, so prefix is one entry longer than
nums and prefix[0] = 0 is the empty sum. That extra slot is what removes the
special case for a range starting at 0.
  sumRange(0, 2) = prefix[3] - prefix[0] =  1 - ( 0) =  1
  sumRange(2, 5) = prefix[6] - prefix[2] = -3 - (-2) = -1
  sumRange(0, 5) = prefix[6] - prefix[0] = -3 - ( 0) = -3
answer null|1|-1|-3
The only thing to get right is the shift, and both halves of it are deliberate.
right + 1 is what makes the right endpoint inclusive; prefix[left] subtracts
everything strictly before left. Write prefix[right] - prefix[left] and
sumRange(0, 2) returns -2, which is the sum of the first TWO values instead of the
first three.
Note the prefix values are not monotonic -- 0, -2, -2, 1, -4, -2, -3 -- and that
is fine. Only differences are ever read, so negative inputs need no special
handling at all.

Complexity

  • Time — O(1) per query: the prefix array is built once in O(n); each sumRange is a subtraction.
  • Space — O(n): the prefix-sum array.

Common Pitfalls

  • Use prefix[right + 1] so the right endpoint is included.

Full Solution — all languages

class NumArray:
    def __init__(self, nums):
        # prefix[i] is the sum of the first i values, so a range is one subtraction
        self.prefix = [0] * (len(nums) + 1)
        for i, v in enumerate(nums):
            self.prefix[i + 1] = self.prefix[i] + v

    def sumRange(self, left, right):
        return self.prefix[right + 1] - self.prefix[left]
SensAI
Beta
Tap the mic to stop voice mode