|
| 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 | +} |
0 commit comments