Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Sparse Tables & Square-Root Decomposition

Range minimum in O(1) per query, Mo’s algorithm, and the optimal RMQ structure.

If the array never changes, a range minimum takes O(1)O(1) time: precompute the minimum of every range whose length is a power of two, and cover any query with two of them, overlapping harmlessly because min⁡(x,x)=x\min(x, x) = x. When the operation cannot tolerate overlap, when queries arrive offline, or when updates are rare, other ideas take over: disjoint tables, square-root blocks and Mo's clever ordering of queries. And with a few more ideas, range minimum needs only O(n)O(n) preprocessing.

What you’ll learn

  • Build a sparse table in O(nlog⁡n)O(n\log n) and answer idempotent range queries (minimum, maximum, gcd) in O(1)O(1), proving why the overlap is harmless.
  • Answer range queries for any associative operation in O(1)O(1) with a disjoint sparse table.
  • Apply square-root decomposition, and Mo's algorithm for offline range queries in O(nq)O(n\sqrt q) pointer moves, with the lower bound that makes its order optimal in the worst case.
  • Describe range-minimum structures with O(n)O(n) preprocessing and O(1)O(1) queries, and the space lower bound they meet.

Sparse tables: two overlapping blocks

A sparse table stores, for every kk with 2k≤n2^k \le n and every start ii, the minimum of the 2k2^k elements beginning at ii; Bender and Farach-Colton (2000) gave it its name in their work on range minimum queries. Row kk follows from row k−1k-1, because a block of length 2k2^k is two blocks of length 2k−12^{k-1}:

sp[0][i]=a[i],sp[k][i]=min⁡(sp[k−1][i], sp[k−1][i+2k−1])\mathrm{sp}[0][i] = a[i], \qquad \mathrm{sp}[k][i] = \min\big(\mathrm{sp}[k-1][i],\ \mathrm{sp}[k-1][i + 2^{k-1}]\big)
⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1 rows of at most nn entries each: O(nlog⁡n)O(n\log n) time and space.
python
def build_sparse(a):                       # sp[k][i] = min(a[i .. i + 2^k - 1]); O(n log n)
    sp = [a[:]]
    k = 1
    while (1 << k) <= len(a):
        prev, half = sp[-1], 1 << (k - 1)
        sp.append([min(prev[i], prev[i + half]) for i in range(len(a) - (1 << k) + 1)])
        k += 1
    return sp

def query_min(sp, l, r):                   # min of a[l..r], inclusive: O(1)
    k = (r - l + 1).bit_length() - 1       # largest k with 2^k <= r - l + 1
    return min(sp[k][l], sp[k][r - (1 << k) + 1])   # two overlapping blocks

bit_length() - 1 is ⌊log⁡2⌋\lfloor\log_2\rfloor. C++ code usually precomputes a table of logarithms or uses GCC's __builtin_clz. Replace min by max, gcd, & or | for the other idempotent operations.

Predict before you look

A sparse table is built over n=106n = 10^6 elements. How many rows does it have, counting k=0,1,2,…k = 0, 1, 2, \dots?

Show the answer

20 rows

219=524,288≤106<2202^{19} = 524{,}288 \le 10^6 < 2^{20}, so kk runs from 0 to 19: 20 rows. Row kk has n−2k+1n - 2^k + 1 entries, about 1.9⋅1071.9\cdot10^7 in all, roughly 76 MB of 4-byte integers. Memory, not time, usually limits sparse tables.

Any associative operation: disjoint sparse tables

Overlap double-counts for sums, products modulo a prime, matrix products or string hashes. Prefix sums rescue sums because subtraction exists, but a general associative operation has no inverse. The disjoint sparse table, as competitive programmers call it, avoids overlap altogether.

For every level k≥1k \ge 1, cut the array into blocks of 2k2^k elements. Inside each block with midpoint mm, store the aggregate of a[i..m−1]a[i..m-1] for every ii in the left half, and of a[m..i]a[m..i] for every ii in the right half. Each level costs O(n)O(n), so the table takes O(nlog⁡n)O(n\log n) time and space.

python
def build_disjoint(a, op):                 # any associative op; O(n log n)
    n = len(a)
    levels = max(1, (n - 1).bit_length())
    t = [None] + [[None] * n for _ in range(levels)]
    for k in range(1, levels + 1):
        size = 1 << k
        for start in range(0, n, size):
            mid = min(start + size // 2, n)       # halves [start, mid), [mid, start + size)
            acc = None
            for i in range(mid - 1, start - 1, -1):   # a[i .. mid-1], growing leftward
                acc = a[i] if acc is None else op(a[i], acc)
                t[k][i] = acc
            acc = None
            for i in range(mid, min(start + size, n)):   # a[mid .. i], growing rightward
                acc = a[i] if acc is None else op(acc, a[i])
                t[k][i] = acc
    return t

def query_disjoint(t, a, op, l, r):        # op over a[l..r]: O(1), one combination
    if l == r:
        return a[l]
    k = (l ^ r).bit_length()               # the level where l and r are split by a midpoint
    return op(t[k][l], t[k][r])

Tested with sums modulo a prime and with products of 2×22\times2 matrices, which do not commute. A single element is answered from the array itself.

Check your understanding

In a disjoint sparse table, which level answers the query [5,9][5, 9]?

  1. Level 2, blocks of 4
  2. Level 3, blocks of 8
  3. Level 4, blocks of 16: 5 and 9 lie in the block [0,15][0, 15], on either side of its midpoint 8
  4. Level 1, blocks of 2
Show the answer

C. Level 4, blocks of 16: 5 and 9 lie in the block [0,15][0, 15], on either side of its midpoint 8

5=010125 = 0101_2 and 9=100129 = 1001_2 first differ in bit 3, so k=bitlen⁡(5⊕9)=bitlen⁡(11002)=4k = \operatorname{bitlen}(5 \oplus 9) = \operatorname{bitlen}(1100_2) = 4: blocks of 16. In the block [0,15][0, 15] with midpoint 8, position 5 stores the aggregate of a[5..7]a[5..7] and position 9 that of a[8..9]a[8..9], and one combination finishes the query.

Square-root decomposition and Mo's algorithm

Square-root decomposition trades a logarithm for flexibility. Cut the array into blocks of b≈nb \approx \sqrt n elements and keep a summary per block: its sum or minimum, a sorted copy (to count the elements ≤x\le x in a range in O(nlog⁡n)O(\sqrt n\log n)), or a pending tag for range updates. A query handles at most 2b2b loose elements and n/bn/b summaries, O(n)O(\sqrt n) in all.

The same idea works on time. Keep a static structure, such as prefix sums, plus a list of pending updates; answer each query from the structure and a scan of the pending list; rebuild after every q\sqrt q updates. Over qq operations that costs O(nq+qq)O(n\sqrt q + q\sqrt q), with no tree at all.

Mo's algorithm answers qq queries on a static array offline, when the answer for a window can be updated in O(1)O(1) as the window grows or shrinks by one element, for example the number of distinct values in a[l..r]a[l..r]. It keeps a current window [L,R][L, R] and moves its ends one step at a time, and everything depends on the order of the queries: sort them by the block ⌊l/B⌋\lfloor l/B\rfloor of their left end, and within a block by rr. Competitive programmers named it after Mo Tao, who popularized it in China.

python
def mo_distinct(a, queries):               # offline: distinct values in each a[l..r]
    n, q = len(a), len(queries)
    B = max(1, int(n / max(1, q) ** 0.5))  # block size n / sqrt(q)
    order = sorted(range(q), key=lambda i: (queries[i][0] // B, queries[i][1]))
    cnt, distinct, ans = {}, 0, [0] * q
    def add(x):
        nonlocal distinct
        cnt[x] = cnt.get(x, 0) + 1
        distinct += cnt[x] == 1
    def remove(x):
        nonlocal distinct
        cnt[x] -= 1
        distinct -= cnt[x] == 0
    L, R = 0, -1                           # current window a[L..R], empty
    for i in order:
        l, r = queries[i]
        while R < r: R += 1; add(a[R])     # grow first, then shrink,
        while L > l: L -= 1; add(a[L])     # so no count goes negative
        while R > r: remove(a[R]); R -= 1
        while L < l: remove(a[L]); L += 1
        ans[i] = distinct
    return ans

Each step is an O(1)O(1) add or remove, so the running time is the number of window steps, bounded below. Answers are stored by query index, because the queries are processed out of order.

DerivationO(n√q) window steps
  1. steps of R ≤ nB⋅2n\text{steps of } R\ \le\ \frac{n}{B}\cdot 2n

    Within one block of left ends the queries are sorted by rr, so RR sweeps rightward after at most one jump back when the block begins: at most 2n2n steps per block, over n/Bn/B blocks.

  2. steps of L ≤ qB+2n\text{steps of } L\ \le\ qB + 2n

    Between two queries of the same block, LL moves less than BB; across the changes of block it moves at most 2n2n in total.

  3. B=nq⟹O(qB+n2B)=O(nq)B = \frac{n}{\sqrt q} \quad\Longrightarrow\quad O\Big(qB + \frac{n^2}{B}\Big) = O\big(n\sqrt q\big)

    Balance the two terms, and add O(qlog⁡q)O(q\log q) for sorting:

  4. nq=105⋅105≈3.2⋅107n\sqrt q = 10^5\cdot\sqrt{10^5} \approx 3.2\cdot10^7

    For n=q=105n = q = 10^5 the bound is about 3.2⋅1073.2\cdot10^7 steps; 100,000 random queries took about 4.2⋅1074.2\cdot10^7 in our tests. With n=qn = q this is the familiar O(nn)O(n\sqrt n).

A popular refinement sorts the queries along a Hilbert curve over the (l,r)(l, r) plane, a classical way to tour points, which keeps the O(nq)O(n\sqrt q) bound and often runs faster. Adding time as a third coordinate handles point updates, in about O(n5/3)O(n^{5/3}) steps when nn and qq are of the same order, and Euler tours carry the method to paths in trees.

Check your understanding

Which of these problems suits Mo's algorithm best?

  1. Range sums interleaved with point updates, each answered before the next operation arrives
  2. 2⋅1052\cdot10^5 queries "how many distinct values does a[l..r]a[l..r] contain?" on a fixed array, all known in advance
  3. The minimum of a[l..r]a[l..r] for 10610^6 queries on a fixed array
  4. The number of inversions of the whole array
Show the answer

B. 2⋅1052\cdot10^5 queries "how many distinct values does a[l..r]a[l..r] contain?" on a fixed array, all known in advance

Distinct counts have no small summary that two halves can merge, but a count table grows or shrinks a window by one element in O(1)O(1). With every query known in advance, Mo's order needs O(nq)O(n\sqrt q) steps, about 9⋅1079\cdot10^7 for n=q=2⋅105n = q = 2\cdot10^5.

Optimal range minimum: O(n) preprocessing, O(1) queries

Cut the array into blocks of bb elements. A sparse table over the n/bn/b block minimums has O(nblog⁡n)O\big(\tfrac nb\log n\big) entries, which is O(n)O(n) once b=Θ(log⁡n)b = \Theta(\log n). A query that spans several blocks combines that table's answer for the whole blocks in between with two in-block queries, a suffix of ll's block and a prefix of rr's.

In-block queries are where the cleverness lies. Bender and Farach-Colton tabulate the answers for every possible block shape, and few shapes exist when bb is small. A simpler word-RAM solution, popular in practice with b=64b = 64, stores for each position rr a bitmask of the monotonic stack of its block after processing rr.

python
W = 64                                      # block size: at most one machine word

def build_masks(a):                         # O(n): one monotonic stack per block, as a bitmask
    mask = [0] * len(a)
    for start in range(0, len(a), W):
        stack = 0                           # bit j - start set: position j is on the stack
        for r in range(start, min(start + W, len(a))):
            while stack and a[start + stack.bit_length() - 1] >= a[r]:
                stack ^= 1 << (stack.bit_length() - 1)    # pop the top, the highest bit
            stack |= 1 << (r - start)
            mask[r] = stack                 # positions j <= r with a[j] < a[j+1..r]
    return mask

def in_block_min(a, mask, l, r):            # l and r in the same block: O(1)
    start = l - l % W
    m = mask[r] >> (l - start)              # stack positions >= l
    return a[l + (m & -m).bit_length() - 1] # the lowest of them holds the minimum

A full query takes the minimum of in_block_min on the two partial blocks and a sparse-table lookup over the whole blocks between them. In C++, __builtin_ctzll (a GCC builtin) finds the lowest set bit in one instruction.

DerivationWhy the lowest stacked position holds the minimum
  1. Sr={ j≤r: a[j]<a[t]  for all j<t≤r }S_r = \{\, j \le r :\ a[j] < a[t] \ \text{ for all } j < t \le r \,\}

    After processing rr, the stack of rr's block holds exactly the positions j≤rj \le r in the block whose value is smaller than every later value up to rr, the strict suffix minima:

  2. j∗=min⁡(Sr∩[l,r])=l+ctz⁡(mask[r]≫(l−start))j^* = \min\big(S_r \cap [l, r]\big) = l + \operatorname{ctz}\big(\mathrm{mask}[r] \gg (l - \mathrm{start})\big)

    Let j∗j^* be the rightmost position of the minimum of a[l..r]a[l..r]. It belongs to SrS_r, and no j∈Srj \in S_r with l≤j<j∗l \le j < j^* exists, since such a jj would have a[j]<a[j∗]a[j] < a[j^*]. So j∗j^* is the smallest element of SrS_r that is at least ll, found by a shift and a count of trailing zeros:

  3. O(n) preprocessing,O(1) per queryO(n)\ \text{preprocessing}, \qquad O(1)\ \text{per query}

    Every position is pushed and popped at most once, so the masks take O(n)O(n) time, and a query uses O(1)O(1) word operations: two in-block queries and one sparse-table lookup.

How small can such a structure be? The answers to all range minimum queries determine the shape of the array's Cartesian tree and nothing more, and there are CnC_n shapes (the Catalan number), so a structure that answers without reading the array needs at least log⁡2Cn=2n−O(log⁡n)\log_2 C_n = 2n - O(\log n) bits. Fischer and Heun's 2n+o(n)2n + o(n) bits meet that bound; the lesson Cartesian Trees & Nearest Smaller Values proves it.

Key takeaways

  • A sparse table stores the minimum (or maximum, gcd, AND, OR) of every power-of-two-length range in O(nlog⁡n)O(n\log n) time and space and answers a static range query with two overlapping blocks in O(1)O(1); the overlap is harmless only for associative, commutative, idempotent operations.
  • A disjoint sparse table stores, at each level, aggregates growing away from each block's midpoint; the highest bit in which ll and rr differ picks the level, and one combination answers any associative range query in O(1)O(1).
  • Square-root decomposition keeps a summary per block of about n\sqrt n elements, or batches about q\sqrt q pending updates between rebuilds: O(n)O(\sqrt n) or O(q)O(\sqrt q) per operation with very little machinery.
  • Mo's algorithm sorts offline queries by the block of ll, then by rr, with B=n/qB = n/\sqrt q, and moves its window O(nq)O(n\sqrt q) steps in total; a grid of queries shows that no window-moving order does better in the worst case.
  • Range minimum needs only O(n)O(n) preprocessing for O(1)O(1) queries: a sparse table over the minimums of Θ(log⁡n)\Theta(\log n)-sized blocks plus word-level in-block queries. Fischer and Heun's 2n+o(n)2n + o(n) bits meet the 2n−O(log⁡n)2n - O(\log n) lower bound that counts Cartesian-tree shapes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A sparse table answers a range minimum with two overlapping blocks. Why does the same trick fail for range sums?

  1. Addition is not associative
  2. The elements in the overlap would be added twice, and addition is not idempotent
  3. The table would need O(n2)O(n^2) space for sums
  4. Sums of power-of-two blocks always overflow
Show the answer

B. The elements in the overlap would be added twice, and addition is not idempotent

The overlap is harmless only when x∘x=xx \circ x = x. For minimum, maximum and gcd it is; for addition, the overlapping elements would count twice. Sums of a static array are better served by prefix sums, and other non-idempotent operations by a disjoint sparse table.

Question 2

Why can a disjoint sparse table answer range products of matrices when an ordinary sparse table cannot?

  1. Matrix products are idempotent
  2. The disjoint table stores every possible range
  3. Its two stored pieces never overlap and are combined left before right, so associativity alone suffices
  4. It reorders the matrices to make the product commutative
Show the answer

C. Its two stored pieces never overlap and are combined left before right, so associativity alone suffices

The ordinary table needs commutativity and idempotence to survive the overlap. The disjoint table splits [l,r][l, r] at a block midpoint into a[l..m−1]a[l..m-1] and a[m..r]a[m..r], both precomputed, and multiplies them in order: correct for any associative operation.

Question 3

Mo's algorithm runs with n=q=105n = q = 10^5. Which block size balances the movements of the two window ends, and about how many window steps result?

  1. B≈316B \approx 316, about nq≈3⋅107n\sqrt q \approx 3\cdot10^7 steps
  2. B=2B = 2, about 10510^5 steps
  3. B≈17B \approx 17, about nlog⁡2n≈1.7⋅106n\log_2 n \approx 1.7\cdot10^6 steps
  4. B=nB = n, about nq=1010nq = 10^{10} steps
Show the answer

A. B≈316B \approx 316, about nq≈3⋅107n\sqrt q \approx 3\cdot10^7 steps

The left end costs about qBqB steps and the right end about n2/Bn^2/B; they balance at B=n/q≈316B = n/\sqrt q \approx 316, for O(nq)≈3⋅107O(n\sqrt q) \approx 3\cdot10^7 steps. Random queries took about 4.2⋅1074.2\cdot10^7 steps in our tests. Tiny blocks make the right end sweep the array once per block, and a single block degenerates to sorting by rr alone.

Question 4

What makes O(n)O(n) preprocessing with O(1)O(1) range-minimum queries possible?

  1. A sparse table over all nn elements
  2. Sorting the array once and binary-searching each query
  3. Answering the queries in Mo's order
  4. Blocks of Θ(log⁡n)\Theta(\log n) elements: a sparse table over the n/log⁡nn/\log n block minimums takes only O(n)O(n) space, and queries inside a block use word operations or tables of the few block shapes
Show the answer

D. Blocks of Θ(log⁡n)\Theta(\log n) elements: a sparse table over the n/log⁡nn/\log n block minimums takes only O(n)O(n) space, and queries inside a block use word operations or tables of the few block shapes

A sparse table over all elements costs Θ(nlog⁡n)\Theta(n\log n). Shrinking the problem by a log⁡n\log n factor first makes the table linear, and blocks small enough to fit in a word, or with few enough shapes to tabulate, answer the in-block parts in O(1)O(1).

Further reading

  • M. A. Bender & M. Farach-Colton, "The LCA problem revisited," LATIN 2000: Theoretical Informatics, LNCS 1776 (2000), 88–94.
  • J. Fischer & V. Heun, "Space-efficient preprocessing schemes for range minimum queries on static arrays," SIAM Journal on Computing 40(2) (2011), 465–492.
  • D. Harel & R. E. Tarjan, "Fast algorithms for finding nearest common ancestors," SIAM Journal on Computing 13(2) (1984), 338–355.
  • A. Laaksonen, Competitive Programmer's Handbook (2018), chapters 9 and 27.
  • CP-Algorithms, Sparse Table and Sqrt Decomposition.