Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 185: Sparse Table — Advanced Techniques

The sparse table answers Range Minimum Queries (RMQ) in O(1) after O(n log n) preprocessing. It works for any idempotent operation (min, max, gcd, lcm, bitwise AND/OR) where f(a, a) = a.


Core Structure

Precompute st[k][i] = result of the operation on the range [i, i + 2^k - 1].

const int LOG = 20;
int st[LOG][MAXN];
int log2[MAXN];

void build(vector<int>& a) {
    int n = a.size();
    log2[1] = 0;
    for (int i = 2; i <= n; i++) log2[i] = log2[i / 2] + 1;

    for (int i = 0; i < n; i++) st[0][i] = a[i];
    for (int k = 1; k < LOG; 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))]);
}

int query(int l, int r) {
    int k = log2[r - l + 1];
    return min(st[k][l], st[k][r - (1 << k) + 1]);
}

Complexity: Preprocessing O(n log n), query O(1), space O(n log n).


Walkthrough

Array: [3, 1, 4, 1, 5, 9, 2, 6]. Query RMQ(2, 6).

kRange lengthst[k][2]
01a[2] = 4
12min(4, 1) = 1
24min(1, 5) = 1

Query(2,6): length=5, k=floor(log₂5)=2. Answer = min(st[2][2], st[2][3]) = min(1, 1) = 1.


Sparse Table vs Segment Tree

FeatureSparse TableSegment Tree
Query timeO(1)O(log n)
PreprocessingO(n log n)O(n)
UpdatesNot supported (static)O(log n)
OperationsIdempotent onlyAny associative op
SpaceO(n log n)O(n)

Extensions

  • 2D Sparse Table: O(1) RMQ on matrices — O(nm log n log m) space.
  • Disjoint Sparse Table: Supports queries where the range midpoint is unknown — useful for offline RMQ with overlapping ranges.
  • GCD/LCM queries: gcd is idempotent, so sparse table works directly.

Common Mistakes

MistakeFix
Using sparse table for sum queriesSum is not idempotent; overlapping ranges double-count
Trying to update the arraySparse table is static; use segment tree instead
Off-by-one in queryr - (1<<k) + 1 ensures non-overlapping coverage

Practice Problems

#ProblemHint
1Range Minimum Query (SPOJ RMQSQ)Build sparse table for min
2GCD on Subarraysgcd is idempotent — use sparse table
3LCA with RMQ (Euler tour)Reduce LCA to RMQ via Euler tour + depth array
4Sparse Table with ORBitwise OR is idempotent
52D Minimum on SubmatrixExtend to 2D sparse table
6Static Range FrequencyCombine with coordinate compression

See Also