Skip to content

Range Sum Query - Immutable

Answer many range-sum questions on a fixed array in O(1) each, after one prefix-sum pass.

EasyPrefix Sums
Solve on LeetCode

The problem

Design a class NumArray that is built from an integer array nums, which never changes afterwards. sumRange(left, right) returns the sum of nums[left] through nums[right], both ends included. The class may be asked up to 10,000 queries, so each one should be fast.

Input NumArray([4, -2, 7, 1, 5]), sumRange(0, 2), sumRange(1, 4), sumRange(3, 3)

Output [null, 9, 11, 1]

4 - 2 + 7 = 9 and -2 + 7 + 1 + 5 = 11; a range of one element is just that element.

Key constraint: Up to 10,000 numbers and 10,000 queries, so summing every range from scratch could mean about 100 million additions.

How to spot the pattern

  • The array never changes, but you are asked many sum questions about its ranges.
  • Each answer is "everything up to right" minus "everything before left".

The idea

Store prefix[i], the sum of the first i numbers, with prefix[0] = 0. The sum of nums[left..right] is everything up to right minus everything before left, which is prefix[right + 1] - prefix[left]. Building the prefix array takes one pass, and after that every query is two lookups and a subtraction.

Brute force: Loop from left to right on every query, which costs O(n) per query and O(n * q) for q queries.

Step by step

  1. 1In the constructor, make prefix with n + 1 slots and prefix[0] = 0.
  2. 2Fill it left to right with prefix[i + 1] = prefix[i] + nums[i].
  3. 3In sumRange, return prefix[right + 1] - prefix[left].

See the pattern move

The prefix sums pattern on a small example. Step through it, or press play.

Code

class NumArray:

    def __init__(self, nums: List[int]):
        # prefix[i] is the sum of the first i numbers, so prefix[0] = 0
        self.prefix = [0] * (len(nums) + 1)
        for i, num in enumerate(nums):
            self.prefix[i + 1] = self.prefix[i] + num

    def sumRange(self, left: int, right: int) -> int:
        return self.prefix[right + 1] - self.prefix[left]

Complexity

Time

O(1)

Space

O(n)

Each sumRange call is two array reads; the constructor pays O(n) once to build the prefix array.

Watch out for

  • Using prefix[right] - prefix[left], which leaves out nums[right]: prefix[i] covers indices 0 to i - 1.
  • Summing the range inside sumRange: correct, but too slow when the class is queried many times.
  • Overflow with bigger limits: here every prefix sum fits in a 32-bit int (at most 10,000 * 100,000 = 10^9), but larger inputs would need 64-bit sums.

Follow-up questions

What if the array can change between queries?

Then one update could force O(n) prefix changes. A Fenwick tree (binary indexed tree) or a segment tree handles both updates and range sums in O(log n); that is Range Sum Query - Mutable.

How does this extend to a 2D grid?

Store prefix[r][c], the sum of the rectangle above and to the left of (r, c). Any sub-rectangle's sum then takes four lookups: take the big rectangle, subtract the two strips, and add back the corner you subtracted twice.

In Hinglish

Ek baar prefix sums bana lo; phir kisi bhi range ka sum bas prefix[right + 1] - prefix[left] hai.

Related problems