Skip to content

Commit 574ecac

Browse files
feat(trees): add SparseTable for O(1) idempotent range queries (#7797)
* feat(trees): add SparseTable for O(1) idempotent range queries * fix(trees): avoid Objects.requireNonNull to satisfy Infer null analysis
1 parent a1e9429 commit 574ecac

2 files changed

Lines changed: 259 additions & 0 deletions

File tree

Lines changed: 157 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,157 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
import java.util.function.IntBinaryOperator;
4+
5+
/**
6+
* Sparse Table data structure for fast static range queries on an immutable array.
7+
*
8+
* <p>Preprocesses an input array of length {@code n} in {@code O(n log n)} time and
9+
* {@code O(n log n)} space, enabling:
10+
* <ul>
11+
* <li>{@link #query(int, int)} in {@code O(1)} time for idempotent associative
12+
* operations (such as {@code min}, {@code max}, {@code gcd}, bitwise AND/OR).</li>
13+
* <li>{@link #queryAssociative(int, int)} in {@code O(log n)} time for general
14+
* associative operations (such as sum or XOR).</li>
15+
* </ul>
16+
*
17+
* @see <a href="https://cp-algorithms.com/data_structures/sparse-table.html">Sparse Table</a>
18+
*/
19+
public final class SparseTable {
20+
21+
private final int length;
22+
private final int[] logs;
23+
private final int[][] table;
24+
private final IntBinaryOperator operation;
25+
26+
/**
27+
* Builds a Sparse Table over {@code array} using the given associative {@code operation}.
28+
*
29+
* @param array non-empty input array (not modified or retained)
30+
* @param operation associative binary operator combining two elements
31+
* @throws IllegalArgumentException if {@code array} is {@code null} or empty, or if {@code operation} is {@code null}
32+
*/
33+
public SparseTable(int[] array, IntBinaryOperator operation) {
34+
if (array == null || array.length == 0) {
35+
throw new IllegalArgumentException("Input array must not be null or empty.");
36+
}
37+
if (operation == null) {
38+
throw new IllegalArgumentException("Operation must not be null.");
39+
}
40+
41+
this.length = array.length;
42+
this.operation = operation;
43+
this.logs = new int[length + 1];
44+
for (int i = 2; i <= length; i++) {
45+
logs[i] = logs[i >>> 1] + 1;
46+
}
47+
48+
int maxPower = logs[length] + 1;
49+
this.table = new int[maxPower][length];
50+
System.arraycopy(array, 0, table[0], 0, length);
51+
52+
for (int k = 1; k < maxPower; k++) {
53+
int span = 1 << (k - 1);
54+
int limit = length - (1 << k);
55+
for (int i = 0; i <= limit; i++) {
56+
table[k][i] = operation.applyAsInt(table[k - 1][i], table[k - 1][i + span]);
57+
}
58+
}
59+
}
60+
61+
/**
62+
* Creates a Sparse Table configured for {@code O(1)} Range Minimum Queries (RMQ).
63+
*
64+
* @param array non-empty input array
65+
* @return a min-query Sparse Table
66+
*/
67+
public static SparseTable ofMin(int[] array) {
68+
return new SparseTable(array, Math::min);
69+
}
70+
71+
/**
72+
* Creates a Sparse Table configured for {@code O(1)} Range Maximum Queries.
73+
*
74+
* @param array non-empty input array
75+
* @return a max-query Sparse Table
76+
*/
77+
public static SparseTable ofMax(int[] array) {
78+
return new SparseTable(array, Math::max);
79+
}
80+
81+
/**
82+
* Creates a Sparse Table configured for {@code O(1)} Range GCD Queries.
83+
*
84+
* @param array non-empty input array
85+
* @return a GCD-query Sparse Table
86+
*/
87+
public static SparseTable ofGcd(int[] array) {
88+
return new SparseTable(array, SparseTable::gcd);
89+
}
90+
91+
/**
92+
* Queries the inclusive range {@code [left, right]} in {@code O(1)} time.
93+
*
94+
* <p>The configured operation must be both associative and idempotent
95+
* ({@code op(x, x) == x}), such as {@code min}, {@code max}, or {@code gcd}.
96+
*
97+
* @param left inclusive start index ({@code 0 <= left <= right})
98+
* @param right inclusive end index ({@code left <= right < size()})
99+
* @return combined result across {@code [left, right]}
100+
* @throws IndexOutOfBoundsException if indices are out of bounds or {@code left > right}
101+
*/
102+
public int query(int left, int right) {
103+
checkRange(left, right);
104+
int k = logs[right - left + 1];
105+
return operation.applyAsInt(table[k][left], table[k][right - (1 << k) + 1]);
106+
}
107+
108+
/**
109+
* Queries the inclusive range {@code [left, right]} in {@code O(log n)} time
110+
* by splitting the range into disjoint power-of-two blocks.
111+
*
112+
* <p>Valid for any associative operation (even non-idempotent ones like sum or XOR).
113+
*
114+
* @param left inclusive start index ({@code 0 <= left <= right})
115+
* @param right inclusive end index ({@code left <= right < size()})
116+
* @return combined result across {@code [left, right]}
117+
* @throws IndexOutOfBoundsException if indices are out of bounds or {@code left > right}
118+
*/
119+
public int queryAssociative(int left, int right) {
120+
checkRange(left, right);
121+
int k = logs[right - left + 1];
122+
int acc = table[k][left];
123+
int pos = left + (1 << k);
124+
while (pos <= right) {
125+
k = logs[right - pos + 1];
126+
acc = operation.applyAsInt(acc, table[k][pos]);
127+
pos += 1 << k;
128+
}
129+
return acc;
130+
}
131+
132+
/**
133+
* Returns the number of elements in the underlying array.
134+
*
135+
* @return array length
136+
*/
137+
public int size() {
138+
return length;
139+
}
140+
141+
private void checkRange(int left, int right) {
142+
if (left < 0 || right >= length || left > right) {
143+
throw new IndexOutOfBoundsException("Invalid range [" + left + ", " + right + "] for length " + length);
144+
}
145+
}
146+
147+
private static int gcd(int a, int b) {
148+
long curA = Math.abs((long) a);
149+
long curB = Math.abs((long) b);
150+
while (curB != 0L) {
151+
long remainder = curA % curB;
152+
curA = curB;
153+
curB = remainder;
154+
}
155+
return Math.toIntExact(curA);
156+
}
157+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.thealgorithms.datastructures.trees;
2+
3+
import static org.junit.jupiter.api.Assertions.assertEquals;
4+
import static org.junit.jupiter.api.Assertions.assertThrows;
5+
6+
import java.util.Random;
7+
import org.junit.jupiter.api.Test;
8+
9+
class SparseTableTest {
10+
11+
@Test
12+
void testRangeMinimumQueriesAllSubarrays() {
13+
int[] data = {7, 2, 3, 0, 5, 10, 3, 12, 18, -4, 9};
14+
SparseTable st = SparseTable.ofMin(data);
15+
assertEquals(data.length, st.size());
16+
17+
for (int left = 0; left < data.length; left++) {
18+
int expected = data[left];
19+
for (int right = left; right < data.length; right++) {
20+
expected = Math.min(expected, data[right]);
21+
assertEquals(expected, st.query(left, right));
22+
assertEquals(expected, st.queryAssociative(left, right));
23+
}
24+
}
25+
}
26+
27+
@Test
28+
void testRangeMaximumQueriesRandomStress() {
29+
Random rng = new Random(42);
30+
int[] data = rng.ints(50, -500, 500).toArray();
31+
SparseTable st = SparseTable.ofMax(data);
32+
33+
for (int left = 0; left < data.length; left++) {
34+
int expected = data[left];
35+
for (int right = left; right < data.length; right++) {
36+
expected = Math.max(expected, data[right]);
37+
assertEquals(expected, st.query(left, right));
38+
}
39+
}
40+
}
41+
42+
@Test
43+
void testRangeGcdQueriesIncludingZeroAndNegatives() {
44+
int[] data = {12, 18, 0, -24, 36, 15, 30};
45+
SparseTable st = SparseTable.ofGcd(data);
46+
47+
assertEquals(6, st.query(0, 1));
48+
assertEquals(6, st.query(0, 2));
49+
assertEquals(6, st.query(0, 4));
50+
assertEquals(3, st.query(3, 5));
51+
assertEquals(15, st.query(5, 6));
52+
assertEquals(0, st.query(2, 2));
53+
assertEquals(24, st.query(3, 3));
54+
55+
SparseTable minValueGcd = SparseTable.ofGcd(new int[] {Integer.MIN_VALUE, 4});
56+
assertEquals(4, minValueGcd.query(0, 1));
57+
}
58+
59+
@Test
60+
void testAssociativeNonIdempotentSumAndXorQueries() {
61+
int[] data = {3, 1, 4, 1, 5, 9, 2, 6, 5};
62+
SparseTable sumTable = new SparseTable(data, Integer::sum);
63+
SparseTable xorTable = new SparseTable(data, (a, b) -> a ^ b);
64+
65+
for (int left = 0; left < data.length; left++) {
66+
int expectedSum = 0;
67+
int expectedXor = 0;
68+
for (int right = left; right < data.length; right++) {
69+
expectedSum += data[right];
70+
expectedXor ^= data[right];
71+
assertEquals(expectedSum, sumTable.queryAssociative(left, right));
72+
assertEquals(expectedXor, xorTable.queryAssociative(left, right));
73+
}
74+
}
75+
}
76+
77+
@Test
78+
void testSingleElementAndDefensiveCopy() {
79+
int[] data = {42};
80+
SparseTable st = SparseTable.ofMin(data);
81+
data[0] = -999;
82+
83+
assertEquals(1, st.size());
84+
assertEquals(42, st.query(0, 0));
85+
assertEquals(42, st.queryAssociative(0, 0));
86+
}
87+
88+
@Test
89+
void testValidationAndOutOfBoundsExceptions() {
90+
assertThrows(IllegalArgumentException.class, () -> SparseTable.ofMin(null));
91+
assertThrows(IllegalArgumentException.class, () -> new SparseTable(new int[] {1}, null));
92+
assertThrows(IllegalArgumentException.class, () -> SparseTable.ofMin(new int[] {}));
93+
94+
SparseTable st = SparseTable.ofMin(new int[] {1, 2, 3});
95+
assertThrows(IndexOutOfBoundsException.class, () -> st.query(-1, 1));
96+
assertThrows(IndexOutOfBoundsException.class, () -> st.query(0, 3));
97+
assertThrows(IndexOutOfBoundsException.class, () -> st.query(2, 1));
98+
assertThrows(IndexOutOfBoundsException.class, () -> st.queryAssociative(-1, 0));
99+
assertThrows(IndexOutOfBoundsException.class, () -> st.queryAssociative(1, 3));
100+
assertThrows(IndexOutOfBoundsException.class, () -> st.queryAssociative(2, 0));
101+
}
102+
}

0 commit comments

Comments
 (0)