Sparse Tables
Precompute the minimum of every block whose length is a power of two. Any range is then covered by two such blocks, so a range minimum query takes two lookups — as long as the array never changes.
Answers for Power-of-Two Blocks
- Solves – range queries on a static array: the minimum, maximum or gcd of
a[l..r]. - Stores –
st[j][i]= the answer for the block of length 2ʲ that starts at index i. - Size – ⌊log₂ n⌋ + 1 rows of at most n cells: O(n log n) memory.
- Build – O(n log n), once.
- Query – O(1) for min and max; O(log n) for sum.
A sparse table is a precomputed table that answers range queries on an array that does not change. It is the standard way to answer a range minimum query (RMQ) in constant time: build once in O(n log n), and every later question "what is the smallest value between index l and index r?" costs two table reads.
It is called sparse because it does not store the answer for every one of the n² ranges, only for ranges whose length is a power of two. That is enough, because any range can be assembled from at most two of them. The whole structure is a 2-D array; there are no pointers and no tree to walk.
- n = 1: a single row, and every query returns a[l]
- Reject or swap a query with l > r; the formulas assume l ≤ r
- A plain 2-D array: cache-friendly and easy to code
Building the Table Row by Row
- Row 0 –
st[0][i] = a[i]: a block of one value is its own answer. - Row j –
st[j][i] = min(st[j-1][i], st[j-1][i + 2^(j-1)])for every i with i + 2ʲ ≤ n. - Log table – precompute
log[x] = log[x / 2] + 1, withlog[1] = 0, so queries never call a slow logarithm. - Stop – after row ⌊log₂ n⌋, the longest power of two that fits in the array.
The build is dynamic programming on block length. A block of length 2ʲ that starts at i is exactly two blocks of length 2ʲ⁻¹: the one starting at i and the one starting at i + 2ʲ⁻¹. Both answers are already in row j − 1, so each new cell costs one comparison.
Row j has n − 2ʲ + 1 valid starts, because the block has to end inside the array. Summing over the rows gives fewer than n · (log₂ n + 1) cells, so both the time and the memory of the build are O(n log n).
- Fill whole rows in order: row j needs row j − 1 complete
- With 0-based starts, row j holds i = 0 … n − 2ʲ; reading past that is the usual bug
Range Minimum Query in O(1)
- Length – len = r − l + 1.
- Block size – k = log[len], so 2ᵏ ≤ len < 2ᵏ⁺¹.
- Left block –
st[k][l]covers l … l + 2ᵏ − 1. - Right block –
st[k][r − 2ᵏ + 1]covers r − 2ᵏ + 1 … r. - Answer –
min(st[k][l], st[k][r − 2ᵏ + 1]).
Because 2ᵏ is more than half of len, a block starting at l and a block ending at r together reach every index in the range. They usually overlap in the middle. For the minimum that is harmless — seeing a value twice cannot make the smallest value smaller or larger — so the answer is simply the smaller of the two cells.
Operations that tolerate overlap are called idempotent: applying them to a value twice gives the same result as once, so f(x, x) = x. Minimum, maximum, gcd, bitwise AND and bitwise OR are idempotent, and all of them get O(1) queries from a sparse table.
- To return the position of the minimum, store indices and compare the values they point to
- Range maximum uses the same code with max in place of min
Terms, operations, and practical uses
Terms to know
- Range minimum query (RMQ)The smallest value in a[l..r].
- Idempotent operationf(x, x) = x, so overlapping blocks do not change the answer: min, max, gcd, AND, OR.
- DoublingBuilding length 2ʲ answers from two length 2ʲ⁻¹ answers.
- Static arrayAn array that is not modified after the table is built.
Related lessons
- Segment treesRange queries with updates in O(log n).
- Fenwick treesPrefix sums with updates in O(log n).
- Prefix sumsO(1) range sums on a static array.
- Lowest common ancestorReduces to RMQ; binary lifting uses the same doubling.
Code in Python, C++ and Java
class SparseTable:
def __init__(self, values):
n = len(values)
# log[x] = floor(log2(x)), so a query can pick its block size in O(1).
self.log = [0] * (n + 1)
for x in range(2, n + 1):
self.log[x] = self.log[x // 2] + 1
self.table = [values[:]]
j = 1
while (1 << j) <= n:
prev = self.table[j - 1]
half = 1 << (j - 1)
row = [min(prev[i], prev[i + half]) for i in range(n - (1 << j) + 1)]
self.table.append(row)
j += 1
def query_min(self, left, right):
k = self.log[right - left + 1]
# Two blocks of length 2^k cover [left, right]; overlap is harmless for min.
return min(self.table[k][left], self.table[k][right - (1 << k) + 1])
values = [4, 6, 1, 5, 7, 3, 8, 2]
st = SparseTable(values)
for j, row in enumerate(st.table):
print(f"length {1 << j}:", row)
for left, right in [(3, 7), (4, 6), (0, 7)]:
print(f"min of [{left}, {right}] =", st.query_min(left, right))#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class SparseTable {
public:
explicit SparseTable(const vector<int>& values) {
int n = values.size();
// log_[x] = floor(log2(x)), so a query can pick its block size in O(1).
log_.assign(n + 1, 0);
for (int x = 2; x <= n; x++) log_[x] = log_[x / 2] + 1;
table_.push_back(values);
for (int j = 1; (1 << j) <= n; j++) {
const vector<int>& prev = table_[j - 1];
int half = 1 << (j - 1);
vector<int> row(n - (1 << j) + 1);
for (int i = 0; i < (int)row.size(); i++) row[i] = min(prev[i], prev[i + half]);
table_.push_back(row);
}
}
int queryMin(int left, int right) const {
int k = log_[right - left + 1];
// Two blocks of length 2^k cover [left, right]; overlap is harmless for min.
return min(table_[k][left], table_[k][right - (1 << k) + 1]);
}
const vector<vector<int>>& table() const { return table_; }
private:
vector<int> log_;
vector<vector<int>> table_;
};
int main() {
SparseTable st({4, 6, 1, 5, 7, 3, 8, 2});
for (size_t j = 0; j < st.table().size(); j++) {
cout << "length " << (1 << j) << ":";
for (size_t i = 0; i < st.table()[j].size(); i++) cout << (i ? ", " : " [") << st.table()[j][i];
cout << "]\n";
}
int queries[][2] = {{3, 7}, {4, 6}, {0, 7}};
for (auto& q : queries) {
cout << "min of [" << q[0] << ", " << q[1] << "] = " << st.queryMin(q[0], q[1]) << "\n";
}
return 0;
}import java.util.Arrays;
public class Main {
static class SparseTable {
final int[] log;
final int[][] table;
SparseTable(int[] values) {
int n = values.length;
// log[x] = floor(log2(x)), so a query can pick its block size in O(1).
log = new int[n + 1];
for (int x = 2; x <= n; x++) log[x] = log[x / 2] + 1;
table = new int[log[n] + 1][];
table[0] = values.clone();
for (int j = 1; j <= log[n]; j++) {
int half = 1 << (j - 1);
table[j] = new int[n - (1 << j) + 1];
for (int i = 0; i < table[j].length; i++) {
table[j][i] = Math.min(table[j - 1][i], table[j - 1][i + half]);
}
}
}
int queryMin(int left, int right) {
int k = log[right - left + 1];
// Two blocks of length 2^k cover [left, right]; overlap is harmless for min.
return Math.min(table[k][left], table[k][right - (1 << k) + 1]);
}
}
public static void main(String[] args) {
SparseTable st = new SparseTable(new int[] {4, 6, 1, 5, 7, 3, 8, 2});
for (int j = 0; j < st.table.length; j++) {
System.out.println("length " + (1 << j) + ": " + Arrays.toString(st.table[j]));
}
int[][] queries = {{3, 7}, {4, 6}, {0, 7}};
for (int[] q : queries) {
System.out.println("min of [" + q[0] + ", " + q[1] + "] = " + st.queryMin(q[0], q[1]));
}
}
}Step through it
Running on a = [4, 6, 1, 5, 7, 3, 8, 2]; queries min(3..7), min(4..6)
Solved Example on Nine Values
- Array – a = [7, 2, 3, 0, 5, 10, 3, 12, 18], n = 9.
- Queries – min(0..4) = 0, min(4..7) = 3, min(7..8) = 12.
Build row by row, writing each cell as the minimum of two cells from the row above. For example st[2][4] = min(st[1][4], st[1][6]) = min(5, 3) = 3, the minimum of a[4..7] = 5, 10, 3, 12. The array has 9 values, so row 3 has only 9 − 8 + 1 = 2 cells.
For each query, find k from the length and read two cells. min(0..4) has length 5, so k = 2 and the blocks are [0..3] and [1..4], overlapping on three values. min(4..7) has length 4, a power of two, so both reads hit the same cell st[2][4] — the overlap is total and still correct.
| Row (length) | i = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|---|
| j = 0 (1) | 7 | 2 | 3 | 0 | 5 | 10 | 3 | 12 | 18 |
| j = 1 (2) | 2 | 2 | 0 | 0 | 5 | 3 | 3 | 12 | — |
| j = 2 (4) | 0 | 0 | 0 | 0 | 3 | 3 | — | — | — |
| j = 3 (8) | 0 | 0 | — | — | — | — | — | — | — |
- Write the full table row by row; mark cells that do not exist
- Show k = ⌊log₂ len⌋ for every query
- Name both cells read, then take their minimum
- A power-of-two length reads the same cell twice
Sum Queries and Why Updates Break It
Sum is not idempotent: adding a value twice changes the total. So a sum query cannot use two overlapping blocks. Instead, split the range into disjoint power-of-two blocks — at most one per bit of the length — and add them. That takes O(log n) per query, which is no better than a Fenwick tree, and a prefix-sum array does O(1) sums with only O(n) memory. Use a sparse table for min, max and gcd, not for sums.
Updates are the real limit. Changing a single value a[p] invalidates every block that contains p — one cell in row 0, two in row 1, four in row 2, and so on, O(n) cells in total. There is no cheap fix-up, so the table must be rebuilt in O(n log n). If the array changes between queries, use a segment tree, which handles both queries and point updates in O(log n).
- Product and XOR are not idempotent either; they need disjoint blocks too
- Updates that arrive in batches: one rebuild per batch can still pay off
Sparse Table vs Segment Tree vs Fenwick Tree
All three answer range queries; they trade query speed against the ability to change the array. Choose a sparse table when the array is fixed and there are many min or max queries. Sparse tables also appear inside other algorithms: LCA (lowest common ancestor) reduces to RMQ on an Euler tour, and binary lifting uses the same doubling table on tree ancestors.
| Sparse table | Segment tree | Fenwick tree | |
|---|---|---|---|
| Build | O(n log n) | O(n) | O(n) |
| Min / max query | O(1) | O(log n) | Not directly |
| Sum query | O(log n) | O(log n) | O(log n) |
| Point update | Rebuild, O(n log n) | O(log n) | O(log n) |
| Memory | O(n log n) | O(n) | O(n) |
| Best for | Static array, many RMQs | Updates and any associative operation | Prefix sums with updates |
- Memory is the price: n = 10⁶ needs about 20 million cells
- For one or two queries, a plain scan beats building any structure