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