</>

303. Range Sum Query - Immutable

Easy
1-D Dynamic Programming Time O(N) Space O(N)
↗ Open on LeetCode Source: Misc

Quick review

Pattern
1-D Dynamic Programming
Time
O(N)
Space
O(N)

Standard Solution (C++)

SummaryGiven an integer array that never changes, answer multiple queries each asking for the sum of elements between two indices (inclusive). The goal is to preprocess the array so each query can be answered in constant time.

Approach
  • Build a prefix-sum array pre of size n+1 where pre[i] holds the sum of the first i elements (pre[0] = 0).
  • For a query [left, right], the answer is pre[right+1] - pre[left], since subtracting the prefix up to left cancels out everything before the window.
  • Construction is O(n) and each query is O(1), which is optimal for immutable arrays with many queries.
#include <vector>
using namespace std;

class NumArray {
public:
    // pre[i] = sum of nums[0..i-1]; pre[0] = 0 as sentinel
    vector<int> pre;

    NumArray(vector<int>& nums) {
        int n = nums.size();
        pre.resize(n + 1, 0);
        for (int i = 0; i < n; ++i)
            pre[i + 1] = pre[i] + nums[i];
    }

    // Sum of nums[left..right] = prefix up to right+1 minus prefix up to left
    int sumRange(int left, int right) {
        return pre[right + 1] - pre[left];
    }
};
Time O(n) constructor, O(1) per query Space O(n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class NumArray {
public:
    NumArray(vector<int>& nums) {
        int N=nums.size();

        accSum.resize(N+1, 0);
        for(int i=0; i<N; ++i){
            accSum[i+1]=accSum[i]+nums[i]; // accSum[1]=nums[0], accSum[2]=nums[0]+nums[1], ...
        }
    }
    
    int sumRange(int left, int right) {
        return accSum[right+1]-accSum[left];
    }

    vector<int> accSum; // accumulated sum
};

// Time Complexity: O(N) for constructor, O(1) for sumRange
// Space Complexity: O(N) for accSum
Time O(N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground C++

Your solution. A driver couldn't be auto-generated for this signature — add a main() that calls the method and prints the result, then Run.

C++ ▶ Runnable Couldn't auto-generate a driver for this signature — edit to add one.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern