PrepStack · Markdown HTML

Sparse table static RMQ

Range-query data structures · HTML

Formal shape

st[k][i] summarizes length 2^k; answer a range with two possibly overlapping largest power-of-two blocks.

Recognition signals

False friends

SignalWhy it is different
Dynamic updatesOne change invalidates many blocks; use a segment tree.
Overlapping blocks for range sumAddition is not idempotent and double-counts overlap; use prefix sums.

Core invariant

st[k][i] exactly summarizes [i,i+2^k), built from two adjacent half-length blocks.

State, transition, and processing order

ItemDefinition
StateA two-dimensional st table and a floor-log table indexed by interval length.
TransitionBuild from short blocks to long; query with k=floor(log2(r-l)) and merge the leading and trailing 2^k blocks.
Frontier / orderConstruction advances by block length; queries jump directly to two blocks and have no dynamic frontier.

Python skeleton

class SparseTableMin:
    def __init__(self, a):
        n = len(a)
        self.log = [0] * (n + 1)
        for i in range(2, n + 1): self.log[i] = self.log[i//2] + 1
        self.st = [a[:]]
        k = 1
        while 1 << k <= n:
            h = 1 << (k-1)
            row = [min(self.st[k-1][i], self.st[k-1][i+h])
                   for i in range(n-(1<<k)+1)]
            self.st.append(row); k += 1
    def query(self, l, r):
        k = self.log[r-l]
        return min(self.st[k][l], self.st[k][r-(1<<k)])

Correctness sketch

  1. Level zero has correct singleton summaries.
  2. Two correct half-blocks produce a correct double-length block.
  3. The selected leading and trailing blocks cover the entire query without leaving it.
  4. Idempotence makes duplicated overlap harmless.

Complexity

TimeSpaceParameters
O(n log n) preprocessing and O(1) queryO(n log n)n array length; Q queries cost O(n log n+Q) total

Edge cases

Error patterns

PatternWhy it fails / fix
Confusing associativity with idempotenceThe overlapping O(1) trick also requires f(x,x)=x.
Taking log of an endpointUse the interval length r-l.
Wrong trailing-block startIt is r-2^k.

Selection and exclusion rules

RelationTemplateBoundary

Original micro-example

PartDetail
ResultMerge blocks [1,5) and [2,6) to get 2.
ScenarioQuery the minimum on [1,6) of static [6,3,8,2,7,5].
WalkthroughThe blocks overlap, but repeated inputs do not affect min.

Recall prompts

My notes