“What is the smallest value between positions l and r?” is called a range minimum query (RMQ). A segment tree answers it in O(log n) and also allows updates. If the array never changes, a sparse table does even better: after O(n log n) preparation, every query takes O(1) time. This lesson builds a sparse table, explains the overlapping trick, and shows which operations it works for.
In this lesson you will learn
- What the sparse table stores
- How each level is built from the one below
- Why two overlapping blocks answer any query in O(1)
- Precomputing log2 values
- Which operations work: min, max, gcd, but not sum
You should know segment trees and bit shifts.
The Idea
Store the minimum of every block whose length is a power of two:
st[k][i] = min of a[i], a[i+1], ..., a[i + 2^k − 1]
- Level 0 is the array itself (blocks of length 1).
- A block of length 2k is two blocks of length 2k−1 side by side, so
st[k][i] = min(st[k−1][i], st[k−1][i + 2^(k−1)]). - There are about log2 n levels, each with up to n entries, so the table uses O(n log n) time and space.
Building and Querying
#include <stdio.h>
#define MAXN 16
#define LOG 5
/* Sparse table: st[k][i] = minimum of a[i .. i + 2^k - 1] */
static int st[LOG][MAXN], lg[MAXN + 1];
static int min(int a, int b) { return a < b ? a : b; }
static void build(const int *a, int n) {
lg[1] = 0;
for (int i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1; /* floor(log2 i) */
for (int i = 0; i < n; i++) st[0][i] = a[i];
for (int k = 1; (1 << k) <= n; k++)
for (int i = 0; i + (1 << k) <= n; i++)
st[k][i] = min(st[k - 1][i], st[k - 1][i + (1 << (k - 1))]);
}
/* Minimum of a[l..r] in O(1): two overlapping blocks cover the range */
static int query(int l, int r) {
int k = lg[r - l + 1];
return min(st[k][l], st[k][r - (1 << k) + 1]);
}
int main(void) {
int a[] = {5, 2, 8, 6, 3, 7, 4, 1};
int n = 8;
build(a, n);
for (int k = 0; (1 << k) <= n; k++) {
printf("len %d:", 1 << k);
for (int i = 0; i + (1 << k) <= n; i++) printf("%3d", st[k][i]);
printf("\n");
}
int qs[][2] = {{0, 3}, {2, 6}, {4, 4}, {0, 7}};
printf("\n");
for (int i = 0; i < 4; i++)
printf("min(a[%d..%d]) = %d\n", qs[i][0], qs[i][1], query(qs[i][0], qs[i][1]));
return 0;
}
Output
len 1: 5 2 8 6 3 7 4 1
len 2: 2 2 6 3 3 4 1
len 4: 2 2 3 3 1
len 8: 1
min(a[0..3]) = 2
min(a[2..6]) = 3
min(a[4..4]) = 3
min(a[0..7]) = 1
- Each printed row is one level. For example, the “len 4” row says the minimum of a[2..5] = {8, 6, 3, 7} is 3.
lg[x]holds ⌊log2 x⌋, built with lg[i] = lg[i / 2] + 1. This avoids slow floating-point logs.- For a query [l, r], let k = lg[r − l + 1], the largest power of two that fits. One block starts at l and another ends at r. Together they cover the whole range, possibly overlapping in the middle.
- For [2, 6], the length is 5, so k = 2 (blocks of 4). The blocks are a[2..5] and a[3..6]. Their minimums are 3 and 3, so the answer is 3.
- A range of length 1, such as [4, 4], uses k = 0 and simply returns a[4].
Which Operations Work?
The overlap means some elements are counted twice. That is harmless when doing an operation twice changes nothing: min(x, x) = x. Such operations are called idempotent.
#include <stdio.h>
#define MAXN 16
#define LOG 5
/* Sparse tables work for any "overlap-friendly" operation: max, min, gcd.
Sum is NOT overlap-friendly, because the overlap would be counted twice. */
static int stmax[LOG][MAXN], stgcd[LOG][MAXN], lg[MAXN + 1];
static int max(int a, int b) { return a > b ? a : b; }
static int gcd(int a, int b) { while (b) { int t = a % b; a = b; b = t; } return a; }
int main(void) {
int a[] = {12, 18, 24, 9, 30, 15, 45, 60};
int n = 8;
lg[1] = 0;
for (int i = 2; i <= n; i++) lg[i] = lg[i / 2] + 1;
for (int i = 0; i < n; i++) stmax[0][i] = stgcd[0][i] = a[i];
for (int k = 1; (1 << k) <= n; k++)
for (int i = 0; i + (1 << k) <= n; i++) {
int h = 1 << (k - 1);
stmax[k][i] = max(stmax[k - 1][i], stmax[k - 1][i + h]);
stgcd[k][i] = gcd(stgcd[k - 1][i], stgcd[k - 1][i + h]);
}
int qs[][2] = {{0, 2}, {1, 4}, {3, 6}, {4, 7}};
for (int q = 0; q < 4; q++) {
int l = qs[q][0], r = qs[q][1], k = lg[r - l + 1], j = r - (1 << k) + 1;
printf("a[%d..%d]: max = %2d, gcd = %2d\n", l, r,
max(stmax[k][l], stmax[k][j]), gcd(stgcd[k][l], stgcd[k][j]));
}
return 0;
}
Output
a[0..2]: max = 24, gcd = 6
a[1..4]: max = 30, gcd = 3
a[3..6]: max = 45, gcd = 3
a[4..7]: max = 60, gcd = 15
- Max and gcd are idempotent, so the same O(1) query works for them. The gcd of a[4..7] = {30, 15, 45, 60} is 15.
- Sum is not idempotent: adding the overlap twice gives the wrong total. For range sums, use a prefix sum array (static) or a Fenwick tree (with updates).
Choosing a Range Query Structure
| Structure | Build | Query | Update | Good for |
|---|---|---|---|---|
| Prefix sums | O(n) | O(1) | O(n) | Static sums |
| Sparse table | O(n log n) | O(1) | Not supported | Static min, max, gcd |
| Fenwick tree | O(n log n) | O(log n) | O(log n) | Sums with updates |
| Segment tree | O(n) | O(log n) | O(log n) | Almost anything, with updates |
Common Mistakes
- Using a sparse table for sums with the overlap trick.
- Building levels past the array end: the condition must be
i + (1 << k) <= n. - Using it on data that changes; one update can affect O(n) entries.
- Computing log with
log2()on doubles, which can round wrongly near powers of two.
Practice Exercises
Exercise 1. For a = {5, 2, 8, 6, 3, 7, 4, 1}, which two blocks answer min(a[1..6])?
Show answer
The length is 6, so k = 2 (blocks of 4): a[1..4] and a[3..6]. Their minimums are 2 and 3, so the answer is 2.
Exercise 2. How many entries does the table need for n = 1000?
Show answer
About n × (⌊log2 n⌋ + 1) = 1000 × 10 = 10 000 entries (slightly fewer, since higher levels are shorter).
Frequently Asked Questions
Can a sparse table answer sum queries at all?
Yes, but not in O(1). Split the range into non-overlapping power-of-two blocks (like the binary digits of its length) and add them, which takes O(log n).
Where are sparse tables used?
They are used for lowest common ancestor queries on trees (after an Euler tour), in suffix array algorithms, and anywhere many minimum queries are asked on fixed data.
Summary
- st[k][i] stores the minimum of the block of length 2k starting at i.
- Each level is built from two blocks of the level below, in O(n log n) total.
- A query uses two overlapping blocks of length 2⌊log len⌋, in O(1).
- It works for idempotent operations on data that does not change.
Next: Lowest Common Ancestor in C.
