Range Sum Query - Immutable

Prefix-sum precomputation — O(1) range sum after O(n) build.

Easy
Time O(n) init Space O(n)
LeetCode
2 min read
design prefix-sum

Problem#

Given a fixed integer array, answer many sumRange(i, j) queries returning the sum of nums[i..j] inclusive.

Examples#

  • nums=[-2,0,3,-5,2,-1]; sumRange(0,2)1.
  • sumRange(2,5)-1; sumRange(0,5)-3.

Constraints#

  • 1 <= n <= 10^4, up to 10^4 queries.

Approach#

Build pre[i+1] = pre[i] + nums[i]. Then sumRange(i,j) = pre[j+1] - pre[i].

Solution#

Range Sum Query - Immutable
class NumArray {
vector<long long> pre;
public:
NumArray(vector<int>& nums) {
pre.assign(nums.size() + 1, 0);
for (int i = 0; i < (int)nums.size(); ++i)
pre[i + 1] = pre[i] + nums[i];
}
int sumRange(int left, int right) {
return (int)(pre[right + 1] - pre[left]);
}
};

Editorial#

Shifting the prefix array by one slot eliminates the i == 0 special case — pre[0] = 0 cleanly represents “sum of empty prefix”. A long long guards against accidental overflow when the input has many large negatives or positives.

Complexity#

  • Time: O(n) init, O(1) per query.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.