Data Structures · Visualization
Sparse Table: Range Query (RMQ)
Sparse Table
Once built, a sparse table answers a min/max range query by picking the largest power of two that fits within the range and combining two (possibly overlapping) precomputed ranges of that size — overlap is fine because min/max are idempotent. Time: O(1) per query after O(n log n) preprocessing. Space: O(1) per query.
Big-O: Build O(n log n); range-min query O(1).
Sparse Table: Range Query (RMQ)
Sparse TableOnce built, a sparse table answers a min/max range query by picking the largest power of two that fits within the range and combining two (possibly overlapping) precomputed ranges of that size — overlap is fine because min/max are idempotent.
How Range Query (RMQ) Works
- Given a query range [L, R], compute length = R - L + 1.
- Find k = floor(log2(length)), the largest power of two ≤ length.
- Look up table[k][L] (covers [L, L+2^k-1]) and table[k][R-2^k+1] (covers [R-2^k+1, R]).
- Combine the two values (e.g. take the min) — their union covers the full range, overlap doesn't affect the result.
Range Query (RMQ) Worked Example
Input: Query min of range [1,6] using the table built above
- length = 6, k = floor(log2(6)) = 2 (covers ranges of length 4)
- table[2][1] covers [1,4] → min = 2
- table[2][3] covers [3,6] → min = 1
- combine(2, 1) = 1
Output: Minimum of range [1,6] is 1, answered in O(1)
Press ▶ Run to watch it step by step.
def range_min(st, l, r): # inclusive query
length = r - l + 1
j = int(math.log2(length))
span = 1 << j
return min(st[j][l], st[j][r - span + 1])
# two overlapping blocks cover the range:
# O(1) per query after O(n log n) preprocessing
# example: range min queryBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Range Query (RMQ) Time & Space Complexity
When to Use Range Query (RMQ)
- Answering thousands of range-min queries on a static array
- Competitive programming range queries
- LCA queries in static trees
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.