Static range queries
Advanced · 11 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
When the data never changes, a sparse table can answer minimum or maximum questions over any range after one preparation step. It stores answers for blocks of 1, 2, 4, 8 items and so on, so any range is covered by two prepared blocks.
Practical use cases
- Web app: Rainfall records in a read-only report. A government weather portal publishes fixed historical rainfall. Visitors pick any date range to see the highest day. Since the data is final, the table is built once on deploy and every later question is two lookups. The page stays light on the server, because no scanning happens at request time and the table sits in memory.
- Web app: Archived analytics for past years. An analytics page for closed financial years lets managers find the best or worst month in a chosen span. Frozen data suits a prepared table, so each answer is just two lookups. Managers can try many ranges in a row and each answer arrives immediately, with no waiting between clicks.
- System: Lowest common ancestor and string tools. Algorithms for finding common ancestors in trees and tools working on text suffix lists need many instant range-minimum answers on data fixed in advance. These algorithms ask millions of such questions, so even a small saving on every one adds up to a big difference.
The story: Kabir's Scoreboard Cheat Sheet
Kabir's school cricket team played a big match. Afterwards, the scorebook was final: no score would ever change. All week, friends came with questions: "What was the highest score between batter 2 and batter 6?" "And between 1 and 7?" Kabir scanned the numbers each time. His friends asked hundreds of questions, and he began to dream of a cheat sheet.
Mira said, "Since the scores never change, prepare answers before anyone asks. Write the best score for every block of 1 batter (just the scores). Then for every block of 2 neighbours, then every block of 4, then 8. Each new row is built from the previous row: a block of 4 is just two blocks of 2 side by side." The cheat sheet had only a few rows.
Then the clever part. A question about 6 batters does not match any block size. But two blocks of 4 placed at the left end and the right end together cover all 6, with a little overlap in the middle. Since the best of the overlap is the same whichever block you read it from, the answer is simply the bigger of the two ready answers. Two lookups per question, no matter how long the range. This is a sparse table, the classic tool for static range queries.
How to spot this problem, and where you need it
You must answer huge numbers of min or max questions on data that is fixed and never updated, and even a segment tree feels heavier than needed.
Signs you need it
- The data is historical, archived or loaded once, and nobody edits it.
- There are millions of range queries, so every extra step matters.
- The question is for the smallest or largest value (min, max, gcd) in a range.
- You can afford extra memory and a bit of start-up time.
Where to use it in a project
- Read-only reports over historical or archived data in portals.
- Preparation steps for algorithms that need many fast range-minimum questions.
The solution
Prepare once: for every start position store the best value over the next 1, 2, 4, 8 and so on items, building each row from the previous one. To answer a range, pick the largest block size that fits inside it, then take the best of two blocks: one starting at the left end and one ending at the right end. They may overlap, which is fine for min and max.
Payoff: Before: scanning the range for every question. After: one quick preparation, then two lookups per question.
Explain it like I am 8
You have photos of the same row of toys taken in different zoom levels. For every starting toy you wrote down the tallest toy among the next 1, then 2, then 4, then 8 toys. To answer any question, pick the biggest "zoom" that fits, look at both ends of your range, and take the taller of the two notes. Overlapping is fine because "tallest" does not mind seeing the same toy twice.
How it works, step by step
- Level 0 is the data itself: blocks of 1.
- Level 1, 2, 3... For each start position, answer for a block of 2, 4, 8... made by combining two blocks from the level below.
- Stop when the block size would be longer than the whole data.
- To answer l to r: find the biggest block size that fits inside the range length (doubling 1, 2, 4, 8... until you would pass it).
- Combine two blocks of that size: one starting at l, one ending at r. They may overlap, which is fine for max, min and similar picks.
The code in four languages
PHP
<?php
// table[k][i] = best (max) of the block of 2^k items starting at i
function buildSparse(array $a): array {
$n = count($a);
$table = [$a]; // level 0: blocks of 1
for ($k = 1; (1 << $k) <= $n; $k++) {
$row = [];
$half = 1 << ($k - 1);
for ($i = 0; $i + (1 << $k) <= $n; $i++) {
$row[] = max($table[$k - 1][$i], $table[$k - 1][$i + $half]); // two smaller blocks joined
}
$table[] = $row;
}
return $table;
}
// Best of l..r (inclusive): two blocks of the biggest fitting size, overlap is fine for max
function queryMax(array $table, int $l, int $r): int {
$len = $r - $l + 1;
$k = 0;
while ((1 << ($k + 1)) <= $len) $k++; // biggest block size that fits: 1, 2, 4, 8...
return max($table[$k][$l], $table[$k][$r - (1 << $k) + 1]);
}
$scores = [5, 3, 7, 2, 6, 4, 1, 8];
$table = buildSparse($scores);
foreach ($table as $k => $row) echo "level $k: " . implode(' ', $row) . PHP_EOL;
echo queryMax($table, 1, 6) . PHP_EOL; // 7 (blocks 1..4 and 3..6)
echo queryMax($table, 4, 7) . PHP_EOL; // 8 (a single block of 4)
echo queryMax($table, 2, 2) . PHP_EOL; // 7 (a single item)JavaScript
// table[k][i] = best (max) of the block of 2^k items starting at i
function buildSparse(a) {
const n = a.length;
const table = [a.slice()]; // level 0: blocks of 1
for (let k = 1; (1 << k) <= n; k++) {
const row = [];
const half = 1 << (k - 1);
for (let i = 0; i + (1 << k) <= n; i++) {
row.push(Math.max(table[k - 1][i], table[k - 1][i + half])); // two smaller blocks joined
}
table.push(row);
}
return table;
}
// Best of l..r (inclusive): two blocks of the biggest fitting size, overlap is fine for max
function queryMax(table, l, r) {
const len = r - l + 1;
let k = 0;
while ((1 << (k + 1)) <= len) k++; // biggest block size that fits: 1, 2, 4, 8...
return Math.max(table[k][l], table[k][r - (1 << k) + 1]);
}
const scores = [5, 3, 7, 2, 6, 4, 1, 8];
const table = buildSparse(scores);
table.forEach((row, k) => console.log('level ' + k + ': ' + row.join(' ')));
console.log(queryMax(table, 1, 6)); // 7 (blocks 1..4 and 3..6)
console.log(queryMax(table, 4, 7)); // 8 (a single block of 4)
console.log(queryMax(table, 2, 2)); // 7 (a single item)Java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
// table[k][i] = best (max) of the block of 2^k items starting at i
static List<int[]> buildSparse(int[] a) {
int n = a.length;
List<int[]> table = new ArrayList<>();
table.add(a.clone()); // level 0: blocks of 1
for (int k = 1; (1 << k) <= n; k++) {
int[] prev = table.get(k - 1);
int half = 1 << (k - 1);
int[] row = new int[n - (1 << k) + 1];
for (int i = 0; i < row.length; i++) {
row[i] = Math.max(prev[i], prev[i + half]); // two smaller blocks joined
}
table.add(row);
}
return table;
}
// Best of l..r (inclusive): two blocks of the biggest fitting size, overlap is fine for max
static int queryMax(List<int[]> table, int l, int r) {
int len = r - l + 1;
int k = 0;
while ((1 << (k + 1)) <= len) k++; // biggest block size that fits: 1, 2, 4, 8...
return Math.max(table.get(k)[l], table.get(k)[r - (1 << k) + 1]);
}
public static void main(String[] args) {
int[] scores = {5, 3, 7, 2, 6, 4, 1, 8};
List<int[]> table = buildSparse(scores);
for (int k = 0; k < table.size(); k++) {
String row = Arrays.stream(table.get(k)).mapToObj(String::valueOf).collect(Collectors.joining(" "));
System.out.println("level " + k + ": " + row);
}
System.out.println(queryMax(table, 1, 6)); // 7 (blocks 1..4 and 3..6)
System.out.println(queryMax(table, 4, 7)); // 8 (a single block of 4)
System.out.println(queryMax(table, 2, 2)); // 7 (a single item)
}
}Go
package main
import (
"fmt"
"strings"
)
// buildSparse returns table where table[k][i] = best (max) of the block of 2^k items starting at i.
func buildSparse(a []int) [][]int {
n := len(a)
table := [][]int{append([]int{}, a...)} // level 0: blocks of 1
for k := 1; 1<<k <= n; k++ {
half := 1 << (k - 1)
var row []int
for i := 0; i+(1<<k) <= n; i++ {
row = append(row, max(table[k-1][i], table[k-1][i+half])) // two smaller blocks joined
}
table = append(table, row)
}
return table
}
// queryMax gives the best of l..r (inclusive): two blocks of the biggest fitting size, overlap is fine for max.
func queryMax(table [][]int, l, r int) int {
length := r - l + 1
k := 0
for 1<<(k+1) <= length { // biggest block size that fits: 1, 2, 4, 8...
k++
}
return max(table[k][l], table[k][r-(1<<k)+1])
}
func main() {
scores := []int{5, 3, 7, 2, 6, 4, 1, 8}
table := buildSparse(scores)
for k, row := range table {
parts := make([]string, len(row))
for i, v := range row {
parts[i] = fmt.Sprint(v)
}
fmt.Printf("level %d: %s\n", k, strings.Join(parts, " "))
}
fmt.Println(queryMax(table, 1, 6)) // 7 (blocks 1..4 and 3..6)
fmt.Println(queryMax(table, 4, 7)) // 8 (a single block of 4)
fmt.Println(queryMax(table, 2, 2)) // 7 (a single item)
}Time: Build O(n log n), each query O(1) for max/min · Extra space: O(n log n). You store a few rows of answers (one row per block size) and then every question needs just two lookups. It cannot handle changing data.
Watch out for
- Using the overlapping-blocks trick for sums or counts. The overlap would be counted twice. Use prefix sums for those.
- Using it when the data changes. One change forces a rebuild of many rows. Pick a segment tree instead.
- Choosing a block size that is too big or off by one: it must be the biggest one that is not longer than the range.
Quick check
- Why can two overlapping blocks answer a range maximum correctly?
- The overlap is ignored
- The blocks are sorted
- Seeing a number twice does not change a maximum
- For a range of length 6, which block size do we use?
- 2
- 4
- 8
- When is a sparse table a poor choice?
- When data never changes
- When many questions are asked
- When the data changes often