progress

~/problems / Range queries / Sparse table (static RMQ)

Build a sparse table

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

A sparse table stores the minimum of every window whose length is a power of two. Row k holds table[k][i] = min(values[i : i + 2**k]) for every i where the window fits (n - 2**k + 1 entries).

Write build_sparse_table(values) -> list[list[int]] returning rows k = 0, 1, 2, ... while 2**k <= n. Row 0 is a copy of values; an empty list gives [].

build_sparse_table([5, 2, 4, 7, 1, 3])
# [[5, 2, 4, 7, 1, 3],   # length 1
#  [2, 2, 4, 1, 1],      # length 2
#  [2, 1, 1]]            # length 4

Up to 10**5 values.

⭐ Bonus: computing each window from scratch still passes; a speed test with 100,000 values earns a star for an O(n log n) build that makes row k from row k - 1 (a window of length 2**k is two of length 2**(k-1) side by side).

Show hint

table[k][i] = min(table[k-1][i], table[k-1][i + 2**(k-1)]).

Topic: Sparse table (static RMQ). O(n log n) build, O(1) idempotent range queries (min/max/gcd).

0:00
Ctrl ' run · Ctrl ↵ submit
esc