Learn / Advanced structures

Sparse table

A sparse table answers range minimum (or maximum, or GCD) queries in O(1) on an array that never changes. Store the answer for every block of length 2ᵏ; any range is covered by two overlapping blocks of the largest power of two that fits. The sheets this guide follows have no problems for this pattern, so the lesson explains the idea and when to use it.

How to recognise it

  • Many range-minimum queries on a fixed array.
  • No updates at all.
  • An overlap-safe operation: min, max, GCD (but not sum).

Doubling

sp[0][i] = a[i]
sp[k][i] = min(sp[k-1][i], sp[k-1][i + 2^(k-1)])
query(l, r): k = floor(log2(r - l + 1)); min(sp[k][l], sp[k][r - 2^k + 1])

Precompute the logarithms so each query is two lookups.

Common mistakes

  • Using it for sums.
  • Off-by-one in the second block's start.

Problems

No problems listed for this pattern yet.

Check yourself

Why is overlap fine for min but not for sum?

How much memory does it use?

What happens if the array changes?