Example 1
- Input
- 8 4 3 2 4 5 1 1 5 3 2 4 5 6 1 8 3 3
- Output
- 2 1 1 4
The four inclusive intervals have minima 2,1,1,4. The last query contains only the third value.
Preprocess a fixed array to answer inclusive range minimum queries with a Sparse Table. Combine two overlapping power-of-two blocks in constant time.
This page solves CSES Static Range Minimum Queries. Read n q, then n integers, then q pairs a b. For each pair print the minimum element from position a through b inclusive. Input endpoints are one-based; the array never changes. The public task has no difficulty rating. The complete programs below convert each endpoint to zero-based and print one result per line.
1 <= n,q <= 2 × 10^5.1 <= x[i] <= 10^9.1 <= a <= b <= n; endpoints are inclusive and one-based.The four inclusive intervals have minima 2,1,1,4. The last query contains only the third value.
A singleton uses two identical length-one blocks, whose minimum remains that value.
Lengths five and three use overlapping blocks; the final length-two query uses one stored interval at both ends.
Store minima for intervals of lengths 1,2,4,8 and so on. A query need not decompose into many disjoint blocks: choose the largest power of two no longer than the query and cover it with one block at each end. The two blocks overlap, but min(x,x)=x, so repeated elements do not change the result. In Example 1 the query [2,4] has length 3; blocks [2,3] and [3,4] both contain position 3 and their minima are 2 and 4. The answer is 2.
Reveal Sparse Table: intuition, complexity, and code
Preprocessing can remove query work when the data is static. Overlap is safe for idempotent operations such as min, max and gcd; it is unsafe for addition without a different query decomposition.