The Wayback Machine - https://web.archive.org/web/20240818163937/https://www.geeksforgeeks.org/range-sum-query-using-sparse-table/
Open In App

Range sum query using Sparse Table

Last Updated : 21 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

We have an array arr[]. We need to find the sum of all the elements in the range L and R where 0 <= L <= R <= n-1. Consider a situation when there are many range queries.

Examples: 

Input : 3 7 2 5 8 9
        query(0, 5)
        query(3, 5)
        query(2, 4)
Output : 34
         22
         15
Note : array is 0 based indexed
       and queries too.

Since there are no updates/modifications, we use the Sparse table to answer queries efficiently. In a sparse table, we break queries in powers of 2.  

Suppose we are asked to compute sum of 
elements from arr[i] to arr[i+12]. 
We do the following:

// Use sum of 8 (or 23) elements 
table[i][3] = sum(arr[i], arr[i + 1], ...
                               arr[i + 7]).

// Use sum of 4 elements
table[i+8][2] = sum(arr[i+8], arr[i+9], ..
                                arr[i+11]).

// Use sum of single element
table[i + 12][0] = sum(arr[i + 12]).

Our result is sum of above values.

Notice that it took only 4 actions to compute the result over a subarray of size 13. 

Flowchart:

Flowchart


C++




// CPP program to find the sum in a given
// range in an array using sparse table.
 
#include <bits/stdc++.h>
using namespace std;
 
// Because 2^17 is larger than 10^5
const int k = 16;
 
// Maximum value of array
const int N = 1e5;
 
// k + 1 because we need to access
// table[r][k]
long long table[N][k + 1];
 
// it builds sparse table.
void buildSparseTable(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        table[i][0] = arr[i];
 
    for (int j = 1; j <= k; j++)
        for (int i = 0; i <= n - (1 << j); i++)
            table[i][j] = table[i][j - 1] +
               table[i + (1 << (j - 1))][j - 1];
}
 
// Returns the sum of the elements in the range
// L and R.
long long query(int L, int R)
{
    // boundaries of next query, 0-indexed
    long long answer = 0;
    for (int j = k; j >= 0; j--) {
        if (L + (1 << j) - 1 <= R) {
            answer = answer + table[L][j];
 
            // instead of having L', we
            // increment L directly
            L += 1 << j;
        }
    }
    return answer;
}
 
// Driver program.
int main()
{
    int arr[] = { 3, 7, 2, 5, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    buildSparseTable(arr, n);
 
    cout << query(0, 5) << endl;
    cout << query(3, 5) << endl;
    cout << query(2, 4) << endl;
 
    return 0;
}


Java




// Java program to find the sum
// in a given range in an array
// using sparse table.
 
class GFG
{
     
// Because 2^17 is larger than 10^5
static int k = 16;
 
// Maximum value of array
static int N = 100000;
 
// k + 1 because we need
// to access table[r][k]
static long table[][] = new long[N][k + 1];
 
// it builds sparse table.
static void buildSparseTable(int arr[],
                             int n)
{
    for (int i = 0; i < n; i++)
        table[i][0] = arr[i];
 
    for (int j = 1; j <= k; j++)
        for (int i = 0; i <= n - (1 << j); i++)
            table[i][j] = table[i][j - 1] +
            table[i + (1 << (j - 1))][j - 1];
}
 
// Returns the sum of the
// elements in the range L and R.
static long query(int L, int R)
{
    // boundaries of next query,
    // 0-indexed
    long answer = 0;
    for (int j = k; j >= 0; j--)
    {
        if (L + (1 << j) - 1 <= R)
        {
            answer = answer + table[L][j];
 
            // instead of having L', we
            // increment L directly
            L += 1 << j;
        }
    }
    return answer;
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 3, 7, 2, 5, 8, 9 };
    int n = arr.length;
 
    buildSparseTable(arr, n);
 
    System.out.println(query(0, 5));
    System.out.println(query(3, 5));
    System.out.println(query(2, 4));
}
}
 
// This code is contributed
// by Kirti_Mangal


C#




// C# program to find the
// sum in a given range
// in an array using
// sparse table.
 
using System;
 
class GFG
{
    // Because 2^17 is
    // larger than 10^5
    static int k = 16;
     
    // Maximum value
    // of array
    static int N = 100000;
     
    // k + 1 because we
    // need to access table[r,k]
    static long [,]table =
           new long[N, k + 1];
     
    // it builds sparse table.
    static void buildSparseTable(int []arr,
                                 int n)
    {
        for (int i = 0; i < n; i++)
            table[i, 0] = arr[i];
     
        for (int j = 1; j <= k; j++)
            for (int i = 0;    
                     i <= n - (1 << j); i++)
                table[i, j] = table[i, j - 1] +
                table[i + (1 << (j - 1)), j - 1];
    }    
     
    // Returns the sum of the
    // elements in the range
    // L and R.
    static long query(int L, int R)
    {
        // boundaries of next
        // query, 0-indexed
        long answer = 0;
        for (int j = k; j >= 0; j--)
        {
            if (L + (1 << j) - 1 <= R)
            {
                answer = answer +
                         table[L, j];
     
                // instead of having
                // L', we increment
                // L directly
                L += 1 << j;
            }
        }
        return answer;
    }
     
    // Driver Code
    static void Main()
    {
        int []arr = new int[]{3, 7, 2,
                              5, 8, 9};
        int n = arr.Length;
     
        buildSparseTable(arr, n);
     
        Console.WriteLine(query(0, 5));
        Console.WriteLine(query(3, 5));
        Console.WriteLine(query(2, 4));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)


Python3




# Python3 program to find the sum in a given
# range in an array using sparse table.
 
# Because 2^17 is larger than 10^5
k = 16
 
# Maximum value of array
n = 100000
 
# k + 1 because we need to access
# table[r][k]
 
table = [[0 for j in range(k+1)] for i in range(n)]
 
# it builds sparse table
def buildSparseTable(arr, n):
    global table, k
    for i in range(n):
        table[i][0] = arr[i]
 
    for j in range(1,k+1):
        for i in range(0,n-(1<<j)+1):
            table[i][j] = table[i][j-1] + \
                          table[i + (1 << (j - 1))][j - 1]
 
# Returns the sum of the elements in the range
# L and R.
def query(L, R):
    global table, k
 
    # boundaries of next query, 0 - indexed
    answer = 0
    for j in range(k,-1,-1):
        if (L + (1 << j) - 1 <= R):
            answer = answer + table[L][j]
 
            # instead of having L ', we
            # increment L directly
            L+=1<<j
 
    return answer
 
# Driver program
if __name__ == '__main__':
    arr = [3, 7, 2, 5, 8, 9]
    n = len(arr)
 
    buildSparseTable(arr, n)
    print(query(0,5))
    print(query(3,5))
    print(query(2,4))
     
# This code is contributed by
# chaudhary_19 (Mayank Chaudhary)


Javascript




<script>
// JavaScript program to find the sum in a given
// range in an array using sparse table.
 
// Because 2^17 is larger than 10^5
const k = 16;
 
// Maximum value of array
const N = 1e5;
 
// k + 1 because we need to access
// table[r][k]
const table = new Array(N).fill(0).map(() => new Array(k + 1).fill(0));
 
// it builds sparse table.
function buildSparseTable(arr, n)
{
    for (let i = 0; i < n; i++)
        table[i][0] = arr[i];
 
    for (let j = 1; j <= k; j++)
        for (let i = 0; i <= n - (1 << j); i++)
            table[i][j] = table[i][j - 1] +
            table[i + (1 << (j - 1))][j - 1];
}
 
// Returns the sum of the elements in the range
// L and R.
function query(L, R)
{
 
    // boundaries of next query, 0-indexed
    let answer = 0;
    for (let j = k; j >= 0; j--)
    {
        if (L + (1 << j) - 1 <= R)
        {
            answer = answer + table[L][j];
 
            // instead of having L', we
            // increment L directly
            L += 1 << j;
        }
    }
    return answer;
}
 
// Driver program.
    let arr = [ 3, 7, 2, 5, 8, 9 ];
    let n = arr.length;
 
    buildSparseTable(arr, n);
 
    document.write(query(0, 5) + "<br>");
    document.write(query(3, 5) + "<br>");
    document.write(query(2, 4) + "<br>");
 
// This code is contributed by Manoj.
</script>


Output:  

34
22
15

This algorithm for answering queries with Sparse Table works in O(k), which is O(log(n)) because we choose minimal k such that 2^k+1 > n.
Time complexity of sparse table construction : Outer loop runs in O(k), inner loop runs in O(n). Thus, in total we get O(n * k) = O(n * log(n)) 

Auxiliary Space: O(n*k), since n*k extra space has been taken.



Previous Article
Next Article

Similar Reads

Range maximum query using Sparse Table
Given an array arr[], the task is to answer queries to find the maximum of all the elements in the index range arr[L...R].Examples: Input: arr[] = {6, 7, 4, 5, 1, 3}, q[][] = {{0, 5}, {3, 5}, {2, 4}} Output: 7 5 5 Input: arr[] = {3, 34, 1}, q[][] = {{1, 2}} Output: 34 Approach: A similar problem to answer range minimum queries has been discussed he
9 min read
Range Minimum Query (Square Root Decomposition and Sparse Table)
We have an array arr[0 . . . n-1]. We should be able to efficiently find the minimum value from index L (query start) to R (query end) where 0 &lt;= L &lt;= R &lt;= n-1. Consider a situation when there are many range queries. Example: Input: arr[] = {7, 2, 3, 0, 5, 10, 3, 12, 18}; query[] = [0, 4], [4, 7], [7, 8]Output: Minimum of [0, 4] is 0 Minim
15+ min read
Generate matrix from given Sparse Matrix using Linked List and reconstruct the Sparse Matrix
Given a sparse matrix mat[][] of dimensions N*M, the task is to construct and represent the original matrix using a Linked List and reconstruct the givensparse matrix. Examples: Input: mat[][] = {{0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 2, 0, 0}, {0, 3, 0, 0, 4}, {0, 0, 5, 0, 0}}Output:Linked list representation: (4, 2, 5) ? (3, 4, 4) ? (3, 1, 3) ?
15+ min read
Sparse Table
We have briefly discussed sparse table in Range Minimum Query (Square Root Decomposition and Sparse Table)Sparse table concept is used for fast queries on a set of static data (elements do not change). It does preprocessing so that the queries can be answered efficiently. Example Problem 1 : Range Minimum Query We have an array arr[0 . . . n-1]. We
15+ min read
Range Minimum Query with Range Assignment
There is an array of n elements, initially filled with zeros. The task is to perform q queries from given queries[][] and there are two types of queries: Type 1 (i.e queries[i][0] == 1): Assign value val = queries[i][3] to all elements on the segment l = queries[i][1] to r = queries[i][2].Type 2 (i.e queries[i][0] == 2): Find the minimum on the seg
15+ min read
Segment Tree for Range Addition and Range Minimum Query
Given an array of size N initially filled with 0s. There are Q queries to be performed, and each query can be one of two types: Type 1 (1, L, R, X): Add X to all elements in the segment from L to R−1.Type 2 (2, L, R): Find the minimum value in the segment from L to R−1.Example: Input: n = 5, q = 6, queries = { {1, 0, 3, 3}, {2, 1, 2}, {1, 1, 4, 4},
15+ min read
Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)
A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix. Why to use Sparse Matrix instead of simple matrix ? Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store onl
15+ min read
Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)
Prerequisite : Sparse Matrix and its representations Set 1 (Using Arrays and Linked Lists)In this post other two methods of sparse matrix representation are discussed. List of ListsDictionary List of Lists (LIL) One of the possible representation of sparse matrix is List of Lists (LIL). Where one list is used to represent the rows and each row cont
15+ min read
Number of prefix sum prime in given range query
Given an array of non-negative integers and range query l, r, find number of prefix sum which are prime numbers in that given range. Prerequisite : Prefix Sum | Primality Test Examples : Input : {2, 3, 4, 7, 9, 10}, l = 1, r = 5; Output : 3 Explanation : prefixSum[0] = arr[l] = 3 prefixSum[1] = prefixSum[0] + arr[2] = 7, prefixSum[2] = prefixSum[1]
9 min read
Range query for Largest Sum Contiguous Subarray
Given an array a[] of size N, and Q queries of two types 1 and 2. For the given query of: Type 1: given l and r (they are positions), and task is to print the Largest sum Contiguous Subarray Type 2: given type, index, and value, update aindex = value. Examples: Input: a[] = {-2, -3, 4, -1, -2, 1, 5, -3} 1st query : 1 5 8 2nd query : 2 1 10 3rd quer
15+ min read
Operations on Sparse Matrices
Given two sparse matrices (Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)), perform operations such as add, multiply or transpose of the matrices in their sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input matrices, one by multiplying the two matrices and one o
15+ min read
Sparse Search
Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string. Examples: Input : arr[] = {"for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"} x = "geeks" Output : 1 Input : arr[] = {"for", "geeks", "", "", "", "", "ide", "practice", "", "", "", "quiz"}, x = "ds" Ou
7 min read
How to store a Sparse Vector efficiently?
A sparse vector is a vector that has a large number of zeros so it takes unwanted space to store these zeroes.The task is to store a given sparse vector efficiently without storing the zeros. Examples: Input: vector = { 2, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0, 0, 5 }
6 min read
Javascript Program to Check if a given matrix is sparse or not
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4
2 min read
What is meant by Sparse Array?
A sparse array or sparse matrix is an array in which most of the elements are zero. Characteristics of Sparse array:The sparse array is an array in which most of the elements have the same value(the default value is zero or null).Sparse matrices are those array that has the majority of their elements equal to zero.A sparse array is an array in whic
6 min read
Prove that Sparse Graph is NP-Complete
Prerequisite: NP-Completeness, NP Class, Sparse Graph, Independent Set Problem: Given graph G = (V, E) and two integers a and b. A set of a number of vertices of G such that there are at most b edges between them is known as the Sparse Subgraph of graph G. Explanation: Sparse Subgraph problem is defined as follows: Input: An undirected graph G = (V
4 min read
Check if a given number is sparse or not
Write a function to check if a given number is Sparse or not. A number is said to be a sparse number if in the binary representation of the number no two or more consecutive bits are set. Example: Input: x = 72Output: trueExplanation: Binary representation of 72 is 01001000. There are no two consecutive 1's in binary representation Input: x = 12Out
7 min read
Find Next Sparse Number
A number is Sparse if there are no two adjacent 1s in its binary representation. For example 5 (binary representation: 101) is sparse, but 6 (binary representation: 110) is not sparse. Given a number x, find the smallest Sparse number which greater than or equal to x. Examples: Input: x = 6 Output: Next Sparse Number is 8 Input: x = 4 Output: Next
10 min read
Sparse Set
How to do the following operations efficiently if there are large number of queries for them. InsertionDeletionSearchingClearing/Removing all the elements. One solution is to use a Self-Balancing Binary Search Tree like Red-Black Tree, AVL Tree, etc. Time complexity of this solution for insertion, deletion and searching is O(Log n).We can also use
15+ min read
LCA for general or n-ary trees (Sparse Matrix DP approach )
In previous posts, we have discussed how to calculate the Lowest Common Ancestor (LCA) for a binary tree and a binary search tree (this, this and this). Now let’s look at a method that can calculate LCA for any tree (not only for binary tree). We use Dynamic Programming with Sparse Matrix Approach in our method. This method is very handy and fast w
15+ min read
Check if a given matrix is sparse or not
A matrix is a two-dimensional data object having m rows and n columns, therefore a total of m*n values. If most of the values of a matrix are 0 then we say that the matrix is sparse. Consider a definition of Sparse where a matrix is considered sparse if the number of 0s is more than half of the elements in the matrix, Examples: Input : 1 0 3 0 0 4
5 min read
Sparse Matrix Representations | Set 3 ( CSR )
If most of the elements in the matrix are zero then the matrix is called a sparse matrix. It is wasteful to store the zero elements in the matrix since they do not affect the results of our computation. This is why we implement these matrices in more efficient representations than the standard 2D Array. Using more efficient representations we can c
11 min read
Range Update without using Lazy Propagation and Point Query in a Segment Tree
Given an array arr[] consisting of N 0s and a 2D array Q[][] consisting of queries of the following two types: 1 L R X: Increment all the elements in the range [L, R] by X.2 X: Print elements at Xth index of the array. Input: arr[] = { 0, 0, 0, 0, 0 }, Q[][] = { { 1, 0, 2, 100 }, { 2, 1 }, { 1, 2, 3, 200 }, { 2, 2 }, { 4 } } Output: 100 300 0 Expla
13 min read
Range Query on array whose each element is XOR of index value and previous element
Consider an arr[] which can be defined as: You are given Q queries of the form [l, r]. The task is to output the value of arr[l] ? arr[l+1] ? ..... ? arr[r-1] ? arr[r] for each query. Examples : Input : q = 3 q1 = { 2, 4 } q2 = { 2, 8 } q3 = { 5, 9 } Output : 7 9 15 The beginning of the array with constraint look like: arr[] = { 0, 1, 3, 0, 4, 1, 7
9 min read
Range and Update Query for Chessboard Pieces
Given N pieces of chessboard all being 'white' and a number of queries Q. There are two types of queries : Update : Given indices of a range [L, R]. Paint all the pieces with their respective opposite color between L and R (i.e. white pieces should be painted with black color and black pieces should be painted with white color).Get : Given indices
15+ min read
Segment Tree | Set 2 (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1. Also, change the value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 &lt;= i &lt;= n-1 and then find the maximum element of given range with updated values.Example : Input : {1, 3, 5, 7, 9, 11}
15+ min read
Range query for count of set bits
Given an array of positive integer and q query which contains two integers, L &amp; R. Task is to find the number of set bits for a given range. Prerequisite : Bitwise Hacks Examples : Input : Arr[] = { 1, 5, 6, 10, 9, 4 } Query : 2 L &amp; R 1 5 2 4 Output : 9 6 Input : Arr[] = { 1, 10, 5, 2, 8, 11, 15 } Query : 2 L &amp; R 2 4 1 5 Output : 4 9 Si
7 min read
Iterative Segment Tree (Range Maximum Query with Node Update)
Given an array arr[0 . . . n-1]. The task is to perform the following operation: Find the maximum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1.Change value of a specified element of the array to a new value x. Given i and x, change A[i] to x, 0 &lt;= i &lt;= n-1. Examples: Input: a[] = {2, 6, 7, 5, 18, 86, 54, 2} Query1: maximum(
14 min read
Iterative Segment Tree (Range Minimum Query)
We have discussed recursive segment tree implementation. In this post, iterative implementation is discussed.Let us consider the following problem understand Segment Trees. We have an array arr[0 . . . n-1]. We should be able to Find the minimum of elements from index l to r where 0 &lt;= l &lt;= r &lt;= n-1 Change value of a specified element of t
14 min read
Multiplication on Array : Range update query in O(1)
Consider an array A[] of integers and the following two types of queries. update(l, r, x): multiply x to all values from A[l] to A[r] (both inclusive).printArray(): Prints the current modified array. Examples: Input: A[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} update(0, 2, 2) update(1, 4, 3) print() update(4, 8, 5) print() Output: 2 6 6 3 15 5 5 5 5 1 Exp
7 min read
three90RightbarBannerImg