Range Sum Query - Immutable
Easy
Topics
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
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
- Build prefix[i] = sum of the first i elements in the constructor.
- sumRange(left, right) returns prefix[right + 1] - prefix[left].
- 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]import java.util.*;
class NumArray {
private final long[] prefix;
public NumArray(int[] nums) {
prefix = new long[nums.length + 1];
for (int i = 0; i < nums.length; i++) prefix[i + 1] = prefix[i] + nums[i];
}
public int sumRange(int left, int right) {
return (int) (prefix[right + 1] - prefix[left]);
}
}#include <bits/stdc++.h>
using namespace std;
class NumArray {
public: NumArray(vector<int>& nums) : prefix_(nums.size() + 1, 0) {
for (size_t i = 0; i < nums.size(); i++) prefix_[i + 1] = prefix_[i] + nums[i];
}
int sumRange(int left, int right) {
return (int)(prefix_[right + 1] - prefix_[left]);
}
private: vector<long long> prefix_;
};class NumArray {
constructor(nums) {
this.prefix = new Array(nums.length + 1).fill(0);
for (let i = 0; i < nums.length; i++) this.prefix[i + 1] = this.prefix[i] + nums[i];
}
sumRange(left, right) {
return this.prefix[right + 1] - this.prefix[left];
}
}