Range Sum Query - Immutables in C++

Suppose we have an array of integers. We have to find the sum of the elements present from index i to j. Two things we have to keep in mind that the array will be immutable, so elements will not be altered, and there will be multiple such queries. So we have to care about the execution time for a large number of queries. Suppose the array is like A = [5, 8, 3, 6, 1, 2, 5], then if query is (A, 0, 3), then it will be 5 + 8 + 3 + 6 = 22.

To solve this, we will follow these steps −

• Take one array B. B[i] will store the sum of elements from 0 to i
• for query perform B[j] – B[i – 1]

Let us see the following implementation to get a better understanding −

Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class NumArray {
public:
vector <int> pre;
NumArray(vector<int>& nums) {
pre.clear();
int n = nums.size();
pre.resize(n);
for(int i = 0; i < n; i++){
if(i == 0)pre[0] = nums[0];
else
pre[i] = pre[i - 1] + nums[i];
}
}
int sumRange(int i, int j) {
if(i == 0)return pre[j];
return pre[j] - pre[i - 1];
}
};
main(){
vector<int> v = {5,8,3,6,1,2,5};
NumArray na(v);
cout<<na.sumRange(0,2)<<endl;
cout<<na.sumRange(2,5)<<endl;
cout<<na.sumRange(0,5)<<endl;
}

Input

Initialize it with [5,8,3,6,1,2,5]
Call sumRange(0,2)
sumRange(2,5)
sumRange(0,5)

Output

16
12
25

Updated on: 28-Apr-2020

87 Views