303. Range Sum Query - Immutable
Problem
Design NumArray(nums) whose sumRange(left, right) returns the sum of nums[left..right] (inclusive). The array never changes, and there are many queries.
Example: NumArray([-2,0,3,-5,2,-1]) → sumRange(0,2) = 1, sumRange(2,5) = −1, sumRange(0,5) = −3
Constraints: up to 10⁴ queries.
Precompute pre[i] = a[0] + … + a[i−1]; then sum(l, r) = pre[r+1] − pre[l].
Complexity: O(n) build, O(1) query.
class NumArray:
def __init__(self, nums: List[int]):
self.pre = [0]
for x in nums:
self.pre.append(self.pre[-1] + x)
def sumRange(self, left: int, right: int) -> int:
return self.pre[right + 1] - self.pre[left]
na = NumArray([-2, 0, 3, -5, 2, -1])
assert [na.sumRange(0, 2), na.sumRange(2, 5), na.sumRange(0, 5)] == [1, -1, -3]
assert NumArray([5]).sumRange(0, 0) == 5
class NumArray {
private final int[] pre;
public NumArray(int[] nums) {
pre = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) pre[i + 1] = pre[i] + nums[i];
}
public int sumRange(int left, int right) { return pre[right + 1] - pre[left]; }
}
type NumArray struct {
pre []int // pre[i] = sum of nums[:i]
}
func Constructor(nums []int) NumArray {
pre := make([]int, len(nums)+1)
for i, x := range nums {
pre[i+1] = pre[i] + x
}
return NumArray{pre: pre}
}
func (this *NumArray) SumRange(left int, right int) int {
return this.pre[right+1] - this.pre[left]
}