Range Sum Query - Immutable (LeetCode 303): Solution and Explanation

Easy
Array
Design
Prefix Sum

Design a NumArray class that takes a fixed integer array and answers many sumRange(left, right) queries, each asking for the sum of nums[left] through nums[right] inclusive.

Intuition

Adding up the range on every call is correct but costs O(n) per query. With up to 10,000 queries on 10,000 numbers, that is up to 100 million additions, almost all of them repeated.

The array never changes, so any work done in the constructor is paid once and reused by every call. The useful thing to precompute is a running total: prefix[k] is the sum of the first k numbers, with prefix[0] = 0.

The sum from left to right is everything before index right + 1 minus everything before index left. Both of those are stored, so each query is one subtraction: prefix[right + 1] - prefix[left]. On a plot of the running total, a range sum is the rise of the curve between two points.

Approach: Prefix sums

  1. In the constructor, create prefix of length n + 1 with prefix[0] = 0.
  2. For each index i, set prefix[i + 1] = prefix[i] + nums[i].
  3. In sumRange(left, right), return prefix[right + 1] - prefix[left].

Step-by-step example

NumArray([-2, 0, 3, -5, 2, -1]), then sumRange(0, 2), sumRange(2, 5), sumRange(0, 5)
  1. The constructor builds prefix = [0, -2, -2, 1, -4, -2, -3]. Each entry adds one more number to the one before it.
  2. sumRange(0, 2) = prefix[3] - prefix[0] = 1 - 0 = 1, which matches -2 + 0 + 3.
  3. sumRange(2, 5) = prefix[6] - prefix[2] = -3 - (-2) = -1, which matches 3 - 5 + 2 - 1.
  4. sumRange(0, 5) = prefix[6] - prefix[0] = -3. The output is [null, 1, -1, -3], where null is the constructor.

Code: Python, Java, C++

1class NumArray:
2    def __init__(self, nums: List[int]):
3        self.prefix = [0]
4        for x in nums:
5            self.prefix.append(self.prefix[-1] + x)
6
7    def sumRange(self, left: int, right: int) -> int:
8        return self.prefix[right + 1] - self.prefix[left]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n) build, O(1) per query

The constructor makes one pass over nums. Each query reads two entries and subtracts.

Space

O(n)

The prefix array stores n + 1 running totals.

Other approaches

Sum on every call (time O(n) per query, space O(1))

Loop from left to right inside sumRange. It needs no extra memory, but each query costs O(n), which is too slow when there are many queries.

Precompute every range (time O(n^2) build, O(1) per query, space O(n^2))

Store the answer for every (left, right) pair in a table. Queries are O(1), but building and storing about n^2 / 2 answers is far more work and memory than the prefix array.

Common mistakes

  • Using prefix[right] - prefix[left], which drops nums[right]. With a leading 0, the end index is right + 1.
  • Building a prefix array without the leading 0, which forces a special case when left is 0.
  • Recomputing the prefix array inside sumRange. It belongs in the constructor so the work happens once.
  • Worrying about overflow: the largest possible sum is 10^4 * 10^5 = 10^9, which still fits in a 32-bit int.

Frequently asked questions

Why does the prefix array have n + 1 entries?

The extra prefix[0] = 0 stands for the sum of no elements. It lets a range starting at index 0 use the same formula as every other range, with no special case.

What changes if the array can be updated?

Then one update would change many prefix entries. That is Range Sum Query - Mutable, which uses a Fenwick tree or segment tree to get O(log n) updates and queries.

Can the same trick work in two dimensions?

Yes. A 2D prefix table stores the sum of every top-left rectangle, and any sub-rectangle is found with four lookups using inclusion and exclusion.

What is the time complexity of each sumRange call?

O(1). It reads two prefix entries and subtracts them, no matter how long the range is.