Sparse Tables
A Sparse Table is a data structure used to answer range queries efficiently on a static array. It is especially useful when we need to perform many queries but the array values do not change. It can answer operations such as range minimum and range maximum queries in O(1) time after O(N log N) preprocessing.
1. What Is a Sparse Table?
A Sparse Table is a data structure that stores answers for intervals whose lengths are powers of two.
Instead of calculating a range answer from the beginning every time, we prepare answers for smaller intervals in advance. Later, we combine these stored answers to answer a query quickly.
2. Why Do We Need Sparse Tables?
Consider this array:
arr = [4, 2, 7, 1, 5, 3, 8, 6]
Suppose we want to find the minimum element between index 2 and index 6.
Range = [7, 1, 5, 3, 8]
Minimum = 1
With a normal array, we may need to visit every element in the requested range. This takes O(N) time in the worst case.
If we have thousands of range queries on the same array, repeating this work can be expensive.
A Sparse Table solves this problem by preprocessing the array and storing answers for intervals of different power-of-two lengths.
3. Understanding Static Arrays
A Sparse Table is mainly designed for static arrays. A static array means that its values do not change after preprocessing.
For example:
arr = [4, 2, 7, 1, 5, 3, 8, 6]
We can ask many questions such as:
- What is the minimum value between indexes 1 and 5?
- What is the maximum value between indexes 2 and 7?
- What is the greatest common divisor between indexes 0 and 6?
However, if an array element changes frequently, a normal Sparse Table is not the best choice because updating its precomputed values can be expensive.
4. The Main Idea: Powers of Two
The most important concept in a Sparse Table is that it stores answers for intervals whose lengths are powers of two.
These lengths are:
1, 2, 4, 8, 16, 32, ...
We represent these interval lengths using powers of two:
| Power | Interval Length |
|---|---|
| 20 | 1 |
| 21 | 2 |
| 22 | 4 |
| 23 | 8 |
| 24 | 16 |
For example, an interval of length 4 contains four consecutive array elements. A Sparse Table stores the answer for every possible interval of length 4.
5. Understanding the Sparse Table Structure
We usually use a two-dimensional table named st.
st[i][j]
Here:
irepresents the starting index of an interval.jrepresents the power of two used as the interval length.- The interval length is
2^j.
For a minimum Sparse Table:
st[i][j] = minimum element
in the interval starting at i
with length 2^j
For example:
st[2][0] = arr[2]
st[2][1] = minimum of arr[2] and arr[3]
st[2][2] = minimum of arr[2], arr[3],
arr[4], and arr[5]
6. Building a Sparse Table
Consider the following array:
arr = [4, 2, 7, 1, 5, 3, 8, 6]
Step 1: Store Intervals of Length 1
When j = 0, the interval length is 20 = 1. Therefore, each table entry stores one array element.
st[i][0] = arr[i]
| Index | Array Value | st[i][0] |
|---|---|---|
| 0 | 4 | 4 |
| 1 | 2 | 2 |
| 2 | 7 | 7 |
| 3 | 1 | 1 |
| 4 | 5 | 5 |
| 5 | 3 | 3 |
| 6 | 8 | 8 |
| 7 | 6 | 6 |
Step 2: Build Intervals of Length 2
When j = 1, the interval length is 2. We combine two intervals of length 1.
st[i][1] = min(
st[i][0],
st[i + 1][0]
)
For example:
st[0][1] = min(4, 2) = 2
st[1][1] = min(2, 7) = 2
st[2][1] = min(7, 1) = 1
st[3][1] = min(1, 5) = 1
Step 3: Build Intervals of Length 4
When j = 2, the interval length is 4. We combine two intervals of length 2.
st[i][2] = min(
st[i][1],
st[i + 2][1]
)
For example:
st[0][2] = min(2, 1) = 1
This represents the minimum value in the interval [0, 3], which contains:
[4, 2, 7, 1]
7. General Formula for Building a Sparse Table
The general formula for a minimum Sparse Table is:
st[i][j] = min(
st[i][j - 1],
st[i + 2^(j - 1)][j - 1]
)
Let's understand this formula:
- The current interval has length 2j.
- We divide it into two equal halves.
- Each half has length 2j-1.
- We calculate the minimum of both halves.
- The smaller value becomes the answer for the complete interval.
Interval = [4, 2, 7, 1]
First half = [4, 2]
Second half = [7, 1]
Minimum of first half = 2
Minimum of second half = 1
Final minimum = min(2, 1) = 1
8. C++ Code to Build a Minimum Sparse Table
void buildSparseTable(vector<int>& arr,
vector<vector<int>>& st) {
int n = arr.size();
int K = 1;
while ((1 << K) <= n) {
K++;
}
st.assign(n, vector<int>(K));
// Store intervals of length 1
for (int i = 0; i < n; i++) {
st[i][0] = arr[i];
}
// Build larger intervals
for (int j = 1; j < K; j++) {
for (int i = 0;
i + (1 << j) <= n;
i++) {
st[i][j] = min(
st[i][j - 1],
st[i + (1 << (j - 1))][j - 1]
);
}
}
}
Explanation
- Calculate the number of levels needed for the table.
- Create a two-dimensional table.
- Copy the original array into the first level.
- Build larger intervals using the two smaller intervals.
- Continue until all valid interval lengths are processed.
9. Answering a Range Minimum Query
After building the Sparse Table, we can answer minimum queries efficiently.
Suppose we want the minimum value between indexes L and R.
First, calculate the length of the requested range:
length = R - L + 1
Next, find the largest power of two that does not exceed this range length.
j = floor(log2(length))
We can then use two intervals of length 2j:
- One interval starting at L.
- Another interval ending at R.
The answer is:
answer = min(
st[L][j],
st[R - (1 << j) + 1][j]
)
10. Example of a Range Minimum Query
Consider:
arr = [4, 2, 7, 1, 5, 3, 8, 6]
Find the minimum from index 2 to index 6.
Step 1: Calculate the range length.
L = 2
R = 6
length = 6 - 2 + 1 = 5
Step 2: Find the largest power of two.
floor(log2(5)) = 2
2^2 = 4
Therefore, we use two intervals, each containing four elements.
Step 3: Select the first interval.
Interval 1 = [2, 5]
Values = [7, 1, 5, 3]
Minimum = 1
Step 4: Select the second interval.
Interval 2 = [3, 6]
Values = [1, 5, 3, 8]
Minimum = 1
Step 5: Combine the answers.
Answer = min(1, 1) = 1
1
11. C++ Code for Range Minimum Query
int query(vector<vector<int>>& st,
int L, int R) {
int length = R - L + 1;
int j = 0;
while ((1 << (j + 1)) <= length) {
j++;
}
return min(
st[L][j],
st[R - (1 << j) + 1][j]
);
}
The function finds the largest power-of-two interval that fits inside the requested range and combines two precomputed answers.
12. Complete C++ Program
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class SparseTable {
private:
vector<vector<int>> st;
int n;
int K;
public:
SparseTable(vector<int>& arr) {
n = arr.size();
K = 1;
while ((1 << K) <= n) {
K++;
}
st.assign(n, vector<int>(K));
// Build intervals of length 1
for (int i = 0; i < n; i++) {
st[i][0] = arr[i];
}
// Build larger intervals
for (int j = 1; j < K; j++) {
for (int i = 0;
i + (1 << j) <= n;
i++) {
st[i][j] = min(
st[i][j - 1],
st[i + (1 << (j - 1))][j - 1]
);
}
}
}
int query(int L, int R) {
int length = R - L + 1;
int j = 0;
while ((1 << (j + 1)) <= length) {
j++;
}
return min(
st[L][j],
st[R - (1 << j) + 1][j]
);
}
};
int main() {
vector<int> arr = {
4, 2, 7, 1, 5, 3, 8, 6
};
SparseTable sp(arr);
cout << "Minimum from index 2 to 6: "
<< sp.query(2, 6) << endl;
cout << "Minimum from index 0 to 3: "
<< sp.query(0, 3) << endl;
cout << "Minimum from index 4 to 7: "
<< sp.query(4, 7) << endl;
return 0;
}
13. Dry Run of the Complete Program
Input array:
[4, 2, 7, 1, 5, 3, 8, 6]
Query 1: Minimum from index 2 to 6
Values = [7, 1, 5, 3, 8]
Minimum = 1
Query 2: Minimum from index 0 to 3
Values = [4, 2, 7, 1]
Minimum = 1
Query 3: Minimum from index 4 to 7
Values = [5, 3, 8, 6]
Minimum = 3
Minimum from index 2 to 6: 1
Minimum from index 0 to 3: 1
Minimum from index 4 to 7: 3
14. Sparse Table for Maximum Queries
A Sparse Table is not limited to minimum queries. We can also use it to find the maximum value in a range.
The building process remains the same. We only replace
min() with max().
st[i][j] = max(
st[i][j - 1],
st[i + (1 << (j - 1))][j - 1]
)
Similarly, the query becomes:
return max(
st[L][j],
st[R - (1 << j) + 1][j]
);
15. Sparse Table for GCD Queries
We can also use a Sparse Table to calculate the greatest common divisor (GCD) of elements in a range.
For this, we use the GCD function while building the table.
st[i][j] = gcd(
st[i][j - 1],
st[i + (1 << (j - 1))][j - 1]
)
During a query:
return gcd(
st[L][j],
st[R - (1 << j) + 1][j]
);
Minimum, maximum, and GCD are examples of idempotent operations. This property allows the two query intervals to overlap safely.
16. Time and Space Complexity
| Operation | Time Complexity |
|---|---|
| Preprocessing | O(N log N) |
| Range Minimum Query | O(1) |
| Range Maximum Query | O(1) |
| Range GCD Query | O(1) |
| Space Complexity | O(N log N) |
Preprocessing takes O(N log N) because we build approximately log N levels, with up to N entries at each level.
A minimum, maximum, or GCD query takes O(1) time because it combines two already calculated table entries.
17. Sparse Table vs Segment Tree vs Fenwick Tree
| Feature | Sparse Table | Segment Tree | Fenwick Tree |
|---|---|---|---|
| Preprocessing | O(N log N) | O(N) | O(N log N) with individual updates |
| Query | O(1) for suitable operations | O(log N) | O(log N) for prefix sums |
| Point Update | Not efficient | O(log N) | O(log N) |
| Space | O(N log N) | O(N) | O(N) |
| Best Use | Static range queries | Flexible range queries and updates | Prefix sums and point updates |
18. Advantages of Sparse Tables
- Very fast O(1) range minimum queries after preprocessing.
- Useful when the array remains unchanged.
- Can support minimum, maximum, and GCD queries.
- Easy to understand once the power-of-two idea is clear.
- Useful when a problem contains a large number of range queries.
19. Limitations of Sparse Tables
- Requires O(N log N) memory.
- Preprocessing takes O(N log N) time.
- Not suitable for frequent point updates.
- The O(1) query technique using overlapping intervals depends on the operation being idempotent.
- More memory is required compared with a basic Fenwick Tree or Segment Tree.
20. Common Mistakes
- Wrong interval length: Remember that level j represents an interval of length 2j.
- Incorrect loop boundaries: Only build an interval when i + 2j is less than or equal to N.
- Wrong second interval: Use R - 2j + 1 as the starting index of the second query interval.
- Using an update operation on a static Sparse Table: The standard Sparse Table does not support efficient point updates.
- Confusing indexes: Make sure the query indexes match the indexing convention used by the array.
- Using overlapping intervals for every operation: The O(1) overlapping-query method is suitable for idempotent operations such as minimum, maximum, and GCD, not ordinary sum.
21. Applications of Sparse Tables
- Range Minimum Query (RMQ).
- Range Maximum Query.
- Range GCD Query.
- Static array query problems.
- Competitive programming problems with many range queries.
- Problems where the input array does not change.
22. Interview Questions
Q1. What is a Sparse Table?
A Sparse Table is a data structure used to answer range queries efficiently on a static array.
Q2. Why are powers of two used?
Powers of two allow us to divide intervals into equal halves and build larger interval answers from smaller ones.
Q3. What does st[i][j] represent?
It represents the answer for an interval starting at index i with length 2j.
Q4. What is the preprocessing complexity?
O(N log N).
Q5. What is the query complexity for a minimum Sparse Table?
O(1).
Q6. Can a Sparse Table handle point updates efficiently?
No. The standard Sparse Table is designed for static arrays. A point update may require rebuilding many precomputed intervals.
Q7. Why can two overlapping intervals be used for minimum queries?
Because the minimum operation is idempotent. Repeating an element does not change the minimum result.
Q8. Can Sparse Tables answer sum queries?
They can be adapted to store interval sums, but the standard O(1) query method using two overlapping intervals does not work for sums because overlapping elements would be counted more than once.
23. Practice Problems
- Build a Sparse Table for a given integer array.
- Find the minimum element between two indexes.
- Find the maximum element between two indexes.
- Answer multiple range minimum queries efficiently.
- Build a Sparse Table for GCD queries.
- Compare the performance of a Sparse Table and a Segment Tree.
- Determine whether an operation can use the overlapping interval query technique.
24. Summary
A Sparse Table is an advanced data structure used for fast range queries on static arrays. It preprocesses intervals of power-of-two lengths and stores their answers.
Remember these important concepts:
- Table: st[i][j] stores an answer for an interval of length 2j.
- Build: Combine two smaller intervals to create a larger interval.
- Query: Use two suitable precomputed intervals.
- Preprocessing: O(N log N).
- Query: O(1) for suitable idempotent operations.
- Space: O(N log N).