Lesson 6 · Advanced structures and algorithms

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.

Sparse Tables concept diagramA 16-cell array. Beneath it, blocks of length 1, 2, 4 and 8 starting at index 2, each split into two halves; below that, the range 3 to 13 covered by two overlapping blocks of length 8.0123456789101112131415build: each block of length 2^j is two blocks of length 2^(j−1)st[0][2] = a[2]st[1][2] = min of two st[0] halvesst[2][2] = min of two st[1] halvesst[3][2] = min of two st[2] halvesquery [3, 13]: length 11, largest power of two ≤ 11 is 8st[3][3]: 3..10st[3][6]: 6..13overlap 6..10 counted twicemin(3..13) = min(st[3][3], st[3][6]) — two reads, O(1)
1

Answers for Power-of-Two Blocks

  1. Solves – range queries on a static array: the minimum, maximum or gcd of a[l..r].
  2. Stores – st[j][i] = the answer for the block of length 2ʲ that starts at index i.
  3. Size – ⌊log₂ n⌋ + 1 rows of at most n cells: O(n log n) memory.
  4. Build – O(n log n), once.
  5. 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
2

Building the Table Row by Row

  1. Row 0 – st[0][i] = a[i]: a block of one value is its own answer.
  2. Row j – st[j][i] = min(st[j-1][i], st[j-1][i + 2^(j-1)]) for every i with i + 2ʲ ≤ n.
  3. Log table – precompute log[x] = log[x / 2] + 1, with log[1] = 0, so queries never call a slow logarithm.
  4. 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
3

Range Minimum Query in O(1)

  1. Length – len = r − l + 1.
  2. Block size – k = log[len], so 2ᵏ ≤ len < 2ᵏ⁺¹.
  3. Left block – st[k][l] covers l … l + 2ᵏ − 1.
  4. Right block – st[k][r − 2ᵏ + 1] covers r − 2ᵏ + 1 … r.
  5. 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
Key reference

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.
Implementation

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]));
        }
    }
}
Watch it run

Step through it

Running on a = [4, 6, 1, 5, 7, 3, 8, 2]; queries min(3..7), min(4..6)

i = 0i = 1i = 2i = 3i = 4i = 5i = 6i = 7len 1len 2len 4len 8a = [4, 6, 1, 5, 7, 3, 8, 2], n = 8i = 0i = 1i = 2i = 3i = 4i = 5i = 6i = 7len 1len 2len 4len 8a = [4, 6, 1, 5, 7, 3, 8, 2], n = 8
Step 1

The array, and an empty table

Row j will hold, for every start i, the minimum of the 2^j values starting at i. Dashed slots do not exist: a block of length 4 cannot start at i = 5 in an array of 8.

Output
1 / 16
4

Solved Example on Nine Values

  1. Array – a = [7, 2, 3, 0, 5, 10, 3, 12, 18], n = 9.
  2. 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.

The sparse table for a = [7, 2, 3, 0, 5, 10, 3, 12, 18]
Row (length)i = 012345678
j = 0 (1)723051031218
j = 1 (2)220053312—
j = 2 (4)000033———
j = 3 (8)00———————
071223304551063712818min(0..4)k=2: min(0, 0) = 0min(4..7)k=2: min(3, 3) = 3min(7..8)k=1: min(12, 12) = 12the two bars of each query always start at l and end at r
  • 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
5

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
6

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.

Range-query structures compared
Sparse tableSegment treeFenwick tree
BuildO(n log n)O(n)O(n)
Min / max queryO(1)O(log n)Not directly
Sum queryO(log n)O(log n)O(log n)
Point updateRebuild, O(n log n)O(log n)O(log n)
MemoryO(n log n)O(n)O(n)
Best forStatic array, many RMQsUpdates and any associative operationPrefix 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