# C++ Range Sum Query Using Sparse Table

Sparsh Table is a data structure, which is used to give results of range queries. It provides the result of most range queries in O(logN) complexity. For maximum range queries, it can also compute the result in O(1).

This tutorial will discuss the problem of a range sum query using a sparse table where we are given an array. We need to find the sum of all elements in range L and R, for example.

Input: arr[ ] = { 2, 4, 1, 5, 6, 3 }
query(1, 3),
query(0,2),
query(1, 5).

Output: 10
7
19

Input: arr[ ] = { 1, 2, 3, 4, 1, 4 }
query(0, 2),
query(2,4),
query(3, 5).

Output: 6
8
9

## Approach to Find the Solution

Firstly We need to create a sparse table to search answers in a sparse table. In creating a Sparse table, we use a 2-D array for storing the answers. In the sparse table, we break queries in the power of 2. After creating a Sparse table, we search for queries in that table and keep on adding value in a variable on the condition of ( Left_index + 2^n - 1 <= Right_index ) where n is the size of the column of a 2-D array.

## Example

C++ Code for the Above Approach

#include <bits/stdc++.h>
using namespace std;
// Maximum value of row of sparse table.
const int m = 1e5;
const int n = 16;
long long SPARSE[m][n + 1];
// query to be found with the help of a sparse table.
long long query(int l, int r){
long long sum = 0;
for (int i = n; i >= 0; i--) {
if (l + (1 << i) - 1 <= r) {
sum = sum + SPARSE[l][i];

l += 1 << i;
}
}
return sum;
}
int main(){
int arr[] = {  1, 2, 3, 4, 1, 4 };
int z = sizeof(arr) / sizeof(arr);
// Building sparse table.
for (int i = 0; i < z; i++)
SPARSE[i] = arr[i];
for (int i = 1; i <= n; i++)
for (int j = 0; j <= z - (1 << j); j++)
SPARSE[j][i] = SPARSE[j][i - 1] + SPARSE[j + (1 << (i - 1))][i - 1];
cout <<"Sum: " << query(0, 2) << endl;
cout <<"Sum: " << query(2, 4) << endl;
cout <<"Sum: " << query(3, 5) << endl;
return 0;
}

## Output

Sum: 6
Sum: 8
Sum: 4

## Conclusion

In this tutorial, we discussed creating a sparse table that is very useful for a range of queries. We discussed a simple approach to solve this problem by sparse table creation and getting queries to result from that table. We also discussed the C++ program for this problem which we can do with programming languages like C, Java, Python, etc. We hope you find this tutorial helpful.