Range Sum Query - Immutable
Difficulty: Easy · Pattern: Prefix Sum · LeetCode #303
Design NumArray, built from an integer array nums, supporting many calls of sumRange(left, right): the sum of nums[left..right] inclusive. The array never changes.
Example
text
NumArray([-2, 0, 3, -5, 2, -1])
sumRange(0, 2) → 1, sumRange(2, 5) → −1, sumRange(0, 5) → −3Hints
- Summing each query is O(n). With many queries, precompute.
- Store P[i] = sum of the first i elements.
Approach
In the constructor, build prefix sums P with P[0] = 0 and P[i+1] = P[i] + nums[i]. Then sumRange(l, r) = P[r + 1] − P[l] in O(1). This is the canonical prefix-sum structure.
Complexity
Time: O(n) build, O(1) per query. Space: O(n).
Python solution
class NumArray:
def __init__(self, nums):
self.p = [0]
for x in nums:
self.p.append(self.p[-1] + x)
def sumRange(self, left, right):
return self.p[right + 1] - self.p[left]JavaScript solution
class NumArray {
constructor(nums) { this.p = [0]; for (const x of nums) this.p.push(this.p[this.p.length - 1] + x); }
sumRange(left, right) { return this.p[right + 1] - this.p[left]; }
}