Data Structures · Visualization
Sparse Table: Build
Sparse Table
A sparse table precomputes answers for all ranges whose length is a power of two, using dynamic programming, so that later range queries over idempotent operations (like min, max, gcd) can be answered in O(1) by combining two overlapping precomputed ranges. Time: O(n log n) to build. Space: O(n log n).
Big-O: Build O(n log n); range-min query O(1).
Sparse Table: Build
Sparse TableA sparse table precomputes answers for all ranges whose length is a power of two, using dynamic programming, so that later range queries over idempotent operations (like min, max, gcd) can be answered in O(1) by combining two overlapping precomputed ranges.
How Build Works
- Compute table[0][i] = array[i] for every index (ranges of length 1).
- For each power j from 1 upward, compute table[j][i] = combine(table[j-1][i], table[j-1][i + 2^(j-1)]), representing a range of length 2^j starting at i.
- Stop once 2^j exceeds the array length.
- Store table as a 2D array indexed by [power][start].
Build Worked Example
Input: Build a min sparse table for [5,2,4,7,6,3,1,8]
- table[0] = [5,2,4,7,6,3,1,8] (length-1 ranges)
- table[1][i] = min of pairs → [2,2,4,6,3,1,1] (length-2 ranges)
- table[2][i] = min of length-2 pairs → [2,2,3,1] (length-4 ranges)
- table[3][0] = min of the two length-4 halves → 1 (length-8 range)
Output: Precomputed table ready to answer any min-range query in O(1)
Press ▶ Run to watch it step by step.
import math
def build_sparse(arr):
n = len(arr)
k = math.floor(math.log2(n)) + 1
st = [arr[:]] # level 0 = the array itself
j = 1
while (1 << j) <= n:
prev = st[j - 1]
span = 1 << (j - 1)
row = [min(prev[i], prev[i + span])
for i in range(n - 2 * span + 1)]
st.append(row)
j += 1
return st
arr = [4, 2, 3, 1, 6, 5, 1, 7] # level j covers 2^j items
# example: build on [5, 2, 4, 7, 6, 3, 1, 8]Behind 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.
Build Time & Space Complexity
When to Use Build
- Range Minimum/Maximum Query (RMQ) preprocessing
- Static array analytics with heavy repeated range queries
- Lowest Common Ancestor via Euler tour + RMQ
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.