Skip to lesson

Sparse table: O(1) static range minimum queries

The Sparse Table precomputes power-of-two intervals using dynamic programming, answering static range minimum queries in O(1) time through algebraic idempotency.

The static RMQ challenge: why prefix sums fail

A static range minimum query (RMQ) asks for the smallest value in [L, R] of an array that never changes after initialization, often hundreds of thousands of times.

Java
int rangeMin(int[] arr, int l, int r) {    int min = arr[l];    for (int i = l + 1; i <= r; i++) {        min = Math.min(min, arr[i]); // O(R - L + 1) work for every query    }    return min;}

Scanning each element from index L to R takes O(N) time per query: For Q queries, the total runtime is O(Q * N), which times out when both N and Q reach one hundred thousand.

We previously solved range sum queries in O(1) time using prefix sum arrays. However, prefix sums rely entirely on the mathematical property of invertibility. Addition is invertible because (A + B) - A = B. Similarly, XOR is invertible because (A ^ B) ^ A = B. Unfortunately, the minimum operation is NOT invertible. If we know that the minimum in prefix [0..R] is 2 and the minimum in prefix [0..L-1] is 2, we cannot deduce whether the minimum of [L..R] is 2 or a larger number like 10, because the value 2 might have occurred inside [0..L-1]. To answer range minimum queries faster without invertibility, we must precalculate answers for strategic sub-intervals. Storing all possible sub-intervals requires O(N^2) space, which is too costly for large arrays. The Sparse Table technique solves this dilemma by precomputing answers only for intervals whose lengths are powers of two: 1, 2, 4, 8, up to the largest power less than or equal to N.

Building the table: dynamic programming on intervals

A Sparse Table is a two-dimensional table st[i][j], where st[i][j] stores the minimum value in the interval starting at index i with length 2^j, covering indices [i, i + 2^j - 1].

SparseTableColumns.javaJava
public class SparseTableColumns {    public static void main(String[] args) {        int[] arr = {5, 2, 8, 1, 9};        int[][] st = new int[arr.length][3];        for (int i = 0; i < arr.length; i++) st[i][0] = arr[i]; // length 1        for (int j = 1; j < 3; j++) {            for (int i = 0; i + (1 << j) <= arr.length; i++) {                st[i][j] = Math.min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);            }            System.out.print("length " + (1 << j) + ":");            for (int i = 0; i + (1 << j) <= arr.length; i++) System.out.print(" " + st[i][j]);            System.out.println();        }    }}
Output
length 2: 2 2 1 1
length 4: 1 1

The first dimension represents the starting index (0 <= i < N), and the second dimension represents the power of two exponent (0 <= j <= floor(log2 N)).

We construct the table using dynamic programming by doubling the interval length at each step. The base cases are intervals of length 2^0 = 1, where st[i][0] simply equals arr[i]. To compute st[i][j], which covers an interval of length 2^j, we split the interval into two equal halves of length 2^(j - 1). The first half starts at index i, and the second half starts at index i + 2^(j - 1). The recurrence relation is: st[i][j] = Math.min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]). Because there are N starting positions and floor(log2 N) + 1 powers of two, the table contains O(N log N) entries. Each entry takes O(1) time to fill from the previous column. Thus, building the entire Sparse Table requires O(N log N) time and O(N log N) memory.

Answering queries in O(1) via idempotency

The defining superpower of the Sparse Table is answering Range Minimum Queries in strictly O(1) time. This constant-time query relies on an algebraic property called idempotency. An operation is idempotent if applying it twice to the same operand produces the same result: min(x, x) = x. For any range [L, R], covering an element multiple times does not alter the overall minimum.

For a query interval [L, R] of total length len = R - L + 1, we find the largest power of two exponent k such that 2^k <= len. Notice that two intervals of length 2^k—one starting at L and extending rightward, and one ending at R and extending leftward—completely cover the entire interval [L, R]. These two intervals are [L, L + 2^k - 1] and [R - 2^k + 1, R]. They may overlap in the middle, but because min is idempotent, overlapping elements are safely compared twice without changing the answer.

Therefore, the query answer is computed in a single comparison: Math.min(st[L][k], st[R - (1 << k) + 1][k]). If we precompute floor(log2(x)) values in an array in O(N) time, finding k takes O(1). The query requires exactly one lookup from two table cells, giving an unbeatable O(1) worst-case time complexity.

Example 1 · Range minimum by scanning, brute force: O(N) per query, O(1) space

ScanMinDemo.javaJava
public class ScanMinDemo {    static int queryMin(int[] arr, int left, int right) {        int min = arr[left];        for (int i = left + 1; i <= right; i++) min = Math.min(min, arr[i]);   // O(N) per query        return min;    }
    public static void main(String[] args) {        int[] arr = {4, 2, 5, 1, 6, 3, 7, 8};        System.out.println("Min in [0, 2]: " + queryMin(arr, 0, 2));        System.out.println("Min in [1, 5]: " + queryMin(arr, 1, 5));        System.out.println("Min in [4, 7]: " + queryMin(arr, 4, 7));    }}
Output
Min in [0, 2]: 2
Min in [1, 5]: 1
Min in [4, 7]: 3

What this code does

  • queryMin() starts with arr[left] and compares every later element in the range.
  • No preparation is needed, but each query can read the whole array.
  • It prints 2, 1 and 3, the same as the sparse table.

Example 2 · Sparse table, optimal for static data: O(1) per query, O(N log N) space

SparseTableRmqDemo.javaJava
public class SparseTableRmqDemo {    private int[][] st;    private int[] logTable;
    public SparseTableRmqDemo(int[] arr) {        int n = arr.length;        int maxK = 31 - Integer.numberOfLeadingZeros(n);        st = new int[n][maxK + 1];
        logTable = new int[n + 1];        for (int i = 2; i <= n; i++) {            logTable[i] = logTable[i / 2] + 1;        }
        for (int i = 0; i < n; i++) {            st[i][0] = arr[i];        }
        for (int j = 1; (1 << j) <= n; j++) {            for (int i = 0; i + (1 << j) <= n; i++) {                st[i][j] = Math.min(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);            }        }    }
    public int queryMin(int l, int r) {        int len = r - l + 1;        int k = logTable[len];        return Math.min(st[l][k], st[r - (1 << k) + 1][k]);    }
    public static void main(String[] args) {        int[] arr = {4, 2, 5, 1, 6, 3, 7, 8};        SparseTableRmqDemo rmq = new SparseTableRmqDemo(arr);        System.out.println("Min in [0, 2]: " + rmq.queryMin(0, 2));        System.out.println("Min in [1, 5]: " + rmq.queryMin(1, 5));        System.out.println("Min in [4, 7]: " + rmq.queryMin(4, 7));    }}
Output
Min in [0, 2]: 2
Min in [1, 5]: 1
Min in [4, 7]: 3

What this code does

  • Subarray [0, 2] is {4, 2, 5}, minimum is 2.
  • Subarray [1, 5] is {2, 5, 1, 6, 3}, minimum is 1.
  • Subarray [4, 7] is {6, 3, 7, 8}, minimum is 3. All queries execute in strictly O(1) time.
  • Why faster: two overlapping blocks of length 2^k cover any range, and minimum ignores the overlap, so a query is two table reads.

Example 3 · Range GCD with a sparse table: O(1) per query

SparseTableGcdDemo.javaJava
public class SparseTableGcdDemo {    private static int gcd(int a, int b) {        return b == 0 ? a : gcd(b, a % b);    }
    public static void main(String[] args) {        int[] arr = {12, 18, 24, 36, 60};        int n = arr.length;        int maxK = 31 - Integer.numberOfLeadingZeros(n);        int[][] st = new int[n][maxK + 1];
        for (int i = 0; i < n; i++) st[i][0] = arr[i];
        for (int j = 1; (1 << j) <= n; j++) {            for (int i = 0; i + (1 << j) <= n; i++) {                st[i][j] = gcd(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);            }        }
        int[] log = new int[n + 1];        for (int i = 2; i <= n; i++) log[i] = log[i / 2] + 1;
        int l = 0, r = 2; // {12, 18, 24} -> gcd is 6        int k = log[r - l + 1];        int ans1 = gcd(st[l][k], st[r - (1 << k) + 1][k]);        System.out.println("GCD [0, 2]: " + ans1);
        l = 2; r = 4; // {24, 36, 60} -> gcd is 12        k = log[r - l + 1];        int ans2 = gcd(st[l][k], st[r - (1 << k) + 1][k]);        System.out.println("GCD [2, 4]: " + ans2);    }}
Output
GCD [0, 2]: 6
GCD [2, 4]: 12

What this code does

  • GCD of 12, 18, 24 is 6.
  • GCD of 24, 36, 60 is 12.
  • Because gcd(x, x) = x is idempotent, overlapping intervals produce exact results in O(1).

Example 4 · Log table precompute: O(N) time

LogTablePrecomputeDemo.javaJava
public class LogTablePrecomputeDemo {    public static void main(String[] args) {        int n = 8;        int[] log = new int[n + 1];        for (int i = 2; i <= n; i++) {            log[i] = log[i / 2] + 1;        }
        for (int len = 1; len <= n; len++) {            int bitLog = 31 - Integer.numberOfLeadingZeros(len);            System.out.println("len=" + len + " -> table=" + log[len] + ", bitwise=" + bitLog);        }    }}
Output
len=1 -> table=0, bitwise=0
len=2 -> table=1, bitwise=1
len=3 -> table=1, bitwise=1
len=4 -> table=2, bitwise=2
len=5 -> table=2, bitwise=2
len=6 -> table=2, bitwise=2
len=7 -> table=2, bitwise=2
len=8 -> table=3, bitwise=3

What this code does

  • log2(1) = 0 because 2^0 <= 1.
  • log2(2) and log2(3) = 1 because 2^1 <= 2, 3 < 4.
  • Both precomputed array and bitwise instructions yield exact powers in O(1).

Fix the error

Fix the compile error

Read the real compiler error, then pick the line that fixes it.

Round 1 of 2

This finds k, the largest power of two that fits in the range [1, 5].

public class SparseFix {
public static void main(String[] args) {
int left = 1, right = 5;
int length = right - left + 1;
int k = 31 - Integer.numberOfLeadingZero(length);
System.out.println(k);
}
}

Error

SparseFix.java:5: error: cannot find symbol
        int k = 31 - Integer.numberOfLeadingZero(length);
  symbol:   method numberOfLeadingZero(int)
  location: class Integer

When to use sparse table vs segment tree

Choosing between a Sparse Table and a Segment Tree comes down to mutability and idempotency. If the underlying array values never change (static data) and the query operation is idempotent (such as minimum, maximum, or greatest common divisor), the Sparse Table is vastly superior because it answers queries in O(1) time compared to O(log N) for a Segment Tree.

However, if the array requires updates, the Sparse Table becomes inefficient. Updating a single element in an array requires updating all power-of-two intervals that contain that index, which takes O(N log N) time in the worst case—essentially requiring a complete rebuild. In contrast, a Segment Tree handles point updates in O(log N) time and range updates in O(log N) time with lazy propagation.

Additionally, non-idempotent operations like range sum (where sum(x, x) != x) cannot use overlapping intervals. To compute a range sum with a Sparse Table, you would have to decompose [L, R] into disjoint power-of-two blocks, which takes O(log N) time—matching a Fenwick tree or Segment Tree, but requiring O(N log N) space instead of O(N). Hence, Sparse Table is the gold standard specifically for static RMQ and GCD queries.

Next step

Check your understanding

10 quick questions