Skip to content
StackDecode
Advanced data structuresAnimated

Sparse Table

Precompute answers for ranges of power-of-two lengths.

Time

O(n log n) build, O(1) query

Extra space

O(n log n)

Use it for

Static range minimum queries.

How it works

  1. A sparse table answers "smallest item in a[l..r]" in O(1), after O(n log n) preparation. It cannot handle updates.
  2. Row k holds, for every start i, the minimum of the 2ᵏ items starting at i. Row 0 is the array itself.
  3. Each entry of row k combines two entries of row k−1: t[k][i] = min(t[k−1][i], t[k−1][i + 2ᵏ⁻¹]).
  4. To answer a query, pick the largest 2ᵏ that fits in the range and take the minimum of two blocks: one starting at l, one ending at r. They may overlap, which is harmless for min and max.

Watch it run

Loading animation…