Sparse tables: O(1) range minimum on a fixed array
1 The smallest value in a range, many times
A problem gives an array that never changes. Then it asks many questions of one kind: what is the smallest value from index l to index r? Our array has eight values:
For l = 1 and r = 6, a loop looks at 7, 3, 9, 5, 8 and 2, and finds 2. But a problem can ask 10⁵ questions about 10⁵ values, and each loop can cover most of the array. That is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
Prefix sums solved this for sums, with one subtraction. A minimum cannot be subtracted, as the previous lesson showed. The running minimum up to index 5 is 3, from index 2. It hides the answer for the range 3 to 5, which is 5.
A sparse table gets around this. After some work up front, it answers each question in O(1), as long as the array never changes.
2 Blocks whose length is a power of two
We calculate the answers for some ranges ahead of time: the ranges whose length is 1, 2, 4, 8, and so on. Each such range is a block, and table[k][i] is the minimum of the 2ᵏ values that start at index i:
table[0]is the array itself. Each block holds one value.table[1][i]is the minimum of indexes i and i + 1.table[2][i]is the minimum of the four values from i to i + 3.
Powers of two make the table cheap to fill. A block of length 2ᵏ is two blocks of length 2ᵏ⁻¹ side by side, and level k − 1 already holds both:
Each entry costs one comparison, and level k needs only level k − 1. A block must end inside the array: its last index, i + 2ᵏ − 1, is at most n − 1. So our 8 values give levels 0 to 3, with 8, 7, 5 and 1 entries.
In the drawing, row k is level k, and the label under each box is the range it covers. Blue marks the two halves an entry reads, and orange marks the entry:
In step 3, the block 1–4 never looks at the array. It reads two answers the level below already holds. The faded boxes stay empty, because a block starting there would run past index 7.
3 Any range is two blocks that may overlap
The range 1 to 6 has length 6, and 6 is not a power of two. But 4 is the largest power of two that fits in it. One block of 4 starts at l, and another block of 4 ends at r. Together they cover the range:
The two blocks overlap at indexes 3 and 4. For a minimum, that does not matter. The 9 and the 5 are looked at twice, but the smaller block minimum is still the smallest value in the range, because min(x, x) = x. An operation with this property is idempotent.
Both blocks are entries in level 2 of the table. The block 1–4 holds 3 and the block 3–6 holds 2, so the answer is min(3, 2) = 2, from two lookups.
For any range from l to r, with len = r − l + 1, we take k as the largest whole number with 2ᵏ ≤ len. That is floor(log₂ len). The block that ends at r starts at r − 2ᵏ + 1:
Two short facts show that this is always right:
- The blocks stay inside the range. 2ᵏ ≤ len, so the block from l ends at or before r, and the block ending at r starts at or after l.
- The blocks leave no gap. k is the largest such power, so 2ᵏ⁺¹ > len. The two blocks together are longer than the range, so they meet or overlap.
4 Finding k, and tracing queries
Each query needs floor(log₂ len) fast. We fill a small table log2Floor once, for every length from 1 to n:
log2Floor[1]is 0.log2Floor[len] = log2Floor[len / 2] + 1, with whole-number division.
The rule works because k is the place of the highest 1 bit of len. For 6, which is 110 in binary, that place is 2. Halving moves the bit down one place, so k drops by exactly 1.
Here are four queries on our array:
| Query | len | k | Block from l | Block ending at r | Answer |
|---|---|---|---|---|---|
| 1 to 6 | 6 | 2 | 1–4: 3 | 3–6: 2 | 2 |
| 0 to 5 | 6 | 2 | 0–3: 3 | 2–5: 3 | 3 |
| 2 to 4 | 3 | 1 | 2–3: 3 | 3–4: 5 | 3 |
| 3 to 3 | 1 | 0 | 3–3: 9 | 3–3: 9 | 9 |
In the second row, the 3 at index 2 sits in both blocks, and min(3, 3) is still 3. In the last row, a range of one value has k = 0, and both blocks are that value.
5 The code
The constructor fills log2Floor and then the levels, from 0 up. rangeMin finds k and reads the two blocks. Each level is its own array, shorter than the one below, as in the drawing.
On our array, the queries 1 to 6, 0 to 5, 2 to 4, 3 to 3 and 0 to 7 return 2, 3, 3, 9 and 2.
The log2Floor table is the simplest way to find k, and it works the same in every language. The language can also find the highest 1 bit directly:
C++
A builtin for k. 31 - __builtin_clz(len) is floor(log₂ len) for a positive int. __builtin_clz counts the 0 bits above the highest 1 bit.
A builtin for k. 31 - Integer.numberOfLeadingZeros(len) is floor(log₂ len) for a positive int. It counts the 0 bits above the highest 1 bit.
A builtin for k. length.bit_length() - 1 is floor(log₂ length) for a positive int. bit_length() is the place of the highest 1 bit, plus 1.
A builtin for k. 31 - Math.clz32(len) is floor(log₂ len) for a positive length. Math.clz32 counts the 0 bits above the highest 1 bit, in 32 bits.
A builtin for k. bits.Len(uint(length)) - 1, from math/bits, is floor(log₂ length) for a positive length. bits.Len is the place of the highest 1 bit, plus 1.
A builtin for k. (usize::BITS - 1 - len.leading_zeros()) as usize is floor(log₂ len) for a positive usize. leading_zeros counts the 0 bits above the highest 1 bit.
A builtin for k. BitOperations.Log2((uint)len), from System.Numerics, is floor(log₂ len) for a positive length.
6 Cost
- Build: O(n log n) time. There are about log n levels, each with up to n entries, and each entry is one comparison. At n = 10⁵ there are 17 levels, so about 10⁵ × 17 = 1.7 × 10⁶ entries.
- Memory: O(n log n). The same 1.7 × 10⁶ numbers. At 4 bytes each, that is about 7 MB.
- Query: O(1). One lookup in
log2Floorand two in the table, whatever the length of the range.
So 10⁵ queries on 10⁵ values take around 2 × 10⁶ steps in all, instead of 10¹⁰. The build is the slow part, and it happens once.
7 Why sum cannot overlap, and what can
The overlap trick needs min(x, x) = x. A sum does not have it. On the range 1 to 6, the block 1–4 sums to 24, and the block 3–6 sums to 24. Together that is 48, but the range sums to 34. The 9 and the 5 in the overlap were added twice, 14 too many.
A sum can use blocks that do not overlap. The length 6 is 4 + 2, so the blocks 1–4 and 5–6 cover the range exactly. That takes up to about log n blocks, O(log n) per query. Prefix sums do it in O(1), so we use those.
The trick works for any operation where x combined with x gives x again:
| Works | Fails |
|---|---|
| min and max | sum |
| gcd: gcd(x, x) = x | product: x × x is not x |
| bitwise AND and OR | XOR: x XOR x = 0 |
The table also cannot take changes. One value sits in up to 2ᵏ blocks of level k, about 2n blocks in all. A change means fixing all of them, or rebuilding the table in O(n log n). When values change between queries, a segment tree answers each range in O(log n) and takes each change in O(log n). It comes after the Fenwick tree, the next lesson.
8 Mistakes, and when to use it
- Blocks that run off the end. Level k has n − 2ᵏ + 1 entries. A loop that runs i up to n − 1 at every level reads past the end of the level below. At level 1 of our array, i = 7 reads
table[0][8], and there is no index 8. - Rounding k up. For the range 1 to 6, rounding log₂ 6 up gives k = 3. Level 3 has one entry, so
table[3][1]does not exist. On a longer array, it would quietly read values outside the range. - Off by one in the second block. The block ending at r starts at r − 2ᵏ + 1. Starting it at r − 2ᵏ gives the block 2–5 for the range 1 to 6. It misses index 6 and returns 3 instead of 2.
- Filling the levels in the wrong order. Level k reads level k − 1, so the outer loop runs over k and the inner loop over i. With the loops swapped, an entry reads
table[k - 1][i + half]before it is filled.
The sign for a sparse table is an array that never changes, and many questions about the minimum or maximum of a range. If values change between questions, use a segment tree. If the question is a sum, use prefix sums.
Practice it
- Range minimum queriesMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.