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.
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 Sparse table to answer queries efficiently. In 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] = sum(arr[i], arr[i + 1], ... arr[i + 7]). // Use sum of 4 elements table[i+8] = sum(arr[i+8], arr[i+9], .. arr[i+11]). // Use sum of single element table[i + 12] = sum(arr[i + 12]). Our result is sum of above values.
Notice that it took only 4 actions to compute result over subarray of size 13.
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))
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Range maximum query using Sparse Table
- Range Minimum Query (Square Root Decomposition and Sparse Table)
- Sparse Table
- Range query for Largest Sum Contiguous Subarray
- Number of prefix sum prime in given range query
- Sparse Set
- LCA for general or n-ary trees (Sparse Matrix DP approach )
- Operations on Sparse Matrices
- Sparse Matrix Representations | Set 3 ( CSR )
- Sparse Search
- How to store a Sparse Vector efficiently?
- Segment Tree | Set 2 (Range Minimum Query)
- Range Query on array whose each element is XOR of index value and previous element
- Difference Array | Range update query in O(1)
- Range and Update Query for Chessboard Pieces
- Segment Tree | Set 2 (Range Maximum Query with Node Update)
- Range query for count of set bits
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Iterative Segment Tree (Range Minimum Query)
- Multiplication on Array : Range update query in O(1)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.