Practice Discrete Math

Algorithms / Sparse Table Rmq

Least You Need to Know: Sparse Tables, RMQ, and Static Idempotent Queries

Sparse tables preprocess answers for intervals of length power of two. They shine on **static arrays** and especially on idempotent operations like minimum, where overlapping power-of-two blocks can answer a query in `O(1)`.

The least you need to know

Key notation

st[i][j] answer on interval starting at i of length `2^j`
RMQ(l, r) minimum on interval `[l, r]`
idempotent combining a value with itself does not change it

Tiny worked example

  • Precompute minimums for all intervals of lengths `1, 2, 4, 8, ...`.
  • To answer RMQ on `[l, r]`, choose the largest `2^k` fitting in the interval.
  • Compare the two precomputed blocks of length `2^k` covering the left and right ends.
  • Overlap is harmless for `min`, which is why the query is constant time.

Common mistakes

How to recognize this kind of problem

Next recommended lesson

Continue through this topic with Least You Need to Know: Stacks, Balanced Delimiters, and Most-Recent Openings.

Least You Need to Know: Stacks, Balanced Delimiters, and Most-Recent Openings

Related lessons

Keep going with nearby lessons in the same topic.

More ways to explore

Start practice