diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 9c582fbe0a3d..e83512b89972 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -10,7 +10,7 @@ jobs:
steps:
- uses: actions/checkout@v7
- name: Set up JDK
- uses: actions/setup-java@v6.0.1
+ uses: actions/setup-java@v6.2.0
with:
java-version: 21
distribution: 'temurin'
diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 82963c044afb..66d626f52876 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -24,13 +24,13 @@ jobs:
uses: actions/checkout@v7
- name: Set up JDK
- uses: actions/setup-java@v6.0.1
+ uses: actions/setup-java@v6.2.0
with:
java-version: 21
distribution: 'temurin'
- name: Initialize CodeQL
- uses: github/codeql-action/init@v4.38.2
+ uses: github/codeql-action/init@v4.39.3
with:
languages: 'java-kotlin'
@@ -38,7 +38,7 @@ jobs:
run: mvn --batch-mode --update-snapshots verify
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v4.38.2
+ uses: github/codeql-action/analyze@v4.39.3
with:
category: "/language:java-kotlin"
@@ -55,12 +55,12 @@ jobs:
uses: actions/checkout@v7
- name: Initialize CodeQL
- uses: github/codeql-action/init@v4.38.2
+ uses: github/codeql-action/init@v4.39.3
with:
languages: 'actions'
- name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v4.38.2
+ uses: github/codeql-action/analyze@v4.39.3
with:
category: "/language:actions"
...
diff --git a/.github/workflows/infer.yml b/.github/workflows/infer.yml
index 7b0973996a41..0b7b1209e4a8 100644
--- a/.github/workflows/infer.yml
+++ b/.github/workflows/infer.yml
@@ -18,7 +18,7 @@ jobs:
- uses: actions/checkout@v7
- name: Set up JDK
- uses: actions/setup-java@v6.0.1
+ uses: actions/setup-java@v6.2.0
with:
java-version: 21
distribution: 'temurin'
diff --git a/.github/workflows/project_structure.yml b/.github/workflows/project_structure.yml
index a70c3240ce08..764832b7b6a6 100644
--- a/.github/workflows/project_structure.yml
+++ b/.github/workflows/project_structure.yml
@@ -16,7 +16,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- - uses: actions/setup-python@v7.0.0
+ - uses: actions/setup-python@v7.1.0
with:
python-version: '3.13'
diff --git a/README.md b/README.md
index d60d5104c385..91766e523bca 100644
--- a/README.md
+++ b/README.md
@@ -17,4 +17,4 @@ These implementations are intended for learning purposes. As such, they may be l
Please read our [Contribution Guidelines](CONTRIBUTING.md) before you contribute to this project.
## Algorithms
-Our [directory](DIRECTORY.md) has the full list of applications.
+Our [directory](DIRECTORY.md) contains the full list of algorithms implemented in Java.
diff --git a/pom.xml b/pom.xml
index 5a166dbf4fe5..f33ae0f435a7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -48,7 +48,7 @@
org.apache.commonscommons-lang3
- 3.21.0
+ 3.22.0org.apache.commons
@@ -61,7 +61,7 @@
maven-surefire-plugin
- 3.6.0
+ 3.6.1
@@ -82,7 +82,7 @@
org.jacocojacoco-maven-plugin
- 0.8.15
+ 0.8.16
@@ -112,14 +112,14 @@
com.puppycrawl.toolscheckstyle
- 14.3.0
+ 14.4.0com.github.spotbugsspotbugs-maven-plugin
- 4.10.4.1
+ 4.10.5.0spotbugs-exclude.xmltrue
diff --git a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
index 8247172e7ee0..00c3fedca71f 100644
--- a/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
+++ b/src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
@@ -4,122 +4,128 @@
* This class contains methods to solve a maze using recursive backtracking.
* The maze is represented as a 2D array where walls, paths, and visited/dead
* ends are marked with different integers.
- *
- * The goal is to find a path from a starting position to the target position
- * (map[6][5]) while navigating through the maze.
*/
public final class MazeRecursion {
+ private static final int[][] FIRST_STRATEGY_DIRECTIONS = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
+ private static final int[][] SECOND_STRATEGY_DIRECTIONS = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
private MazeRecursion() {
}
/**
- * This method solves the maze using the "down -> right -> up -> left"
- * movement strategy.
+ * Solves the maze using the "down -> right -> up -> left" movement strategy,
+ * starting at (1, 1) and targeting (6, 5).
*
- * @param map The 2D array representing the maze (walls, paths, etc.)
- * @return The solved maze with paths marked, or null if no solution exists.
+ * @param map the 2D array representing the maze (walls, paths, etc.)
+ * @return the solved maze with paths marked, or null if no solution exists or a fixed endpoint is outside the maze
+ * @throws IllegalArgumentException if the maze is null, empty, or not rectangular
*/
public static int[][] solveMazeUsingFirstStrategy(int[][] map) {
- if (setWay(map, 1, 1)) {
+ validateMaze(map);
+ if (!isInBounds(map, 1, 1) || !isInBounds(map, 6, 5)) {
+ return null;
+ }
+ if (map[6][5] == 2) {
return map;
}
- return null;
+ return solve(map, 1, 1, 6, 5, FIRST_STRATEGY_DIRECTIONS) ? map : null;
}
/**
- * This method solves the maze using the "up -> right -> down -> left"
- * movement strategy.
+ * Solves the maze using the "up -> right -> down -> left" movement strategy,
+ * starting at (1, 1) and targeting (6, 5).
*
- * @param map The 2D array representing the maze (walls, paths, etc.)
- * @return The solved maze with paths marked, or null if no solution exists.
+ * @param map the 2D array representing the maze (walls, paths, etc.)
+ * @return the solved maze with paths marked, or null if no solution exists or a fixed endpoint is outside the maze
+ * @throws IllegalArgumentException if the maze is null, empty, or not rectangular
*/
public static int[][] solveMazeUsingSecondStrategy(int[][] map) {
- if (setWay2(map, 1, 1)) {
+ validateMaze(map);
+ if (!isInBounds(map, 1, 1) || !isInBounds(map, 6, 5)) {
+ return null;
+ }
+ if (map[6][5] == 2) {
return map;
}
- return null;
+ return solve(map, 1, 1, 6, 5, SECOND_STRATEGY_DIRECTIONS) ? map : null;
}
/**
- * Attempts to find a path through the maze using a "down -> right -> up -> left"
- * movement strategy. The path is marked with '2' for valid paths and '3' for dead ends.
+ * Solves the maze using the "down -> right -> up -> left" movement strategy.
*
- * @param map The 2D array representing the maze (walls, paths, etc.)
- * @param i The current x-coordinate of the ball (row index)
- * @param j The current y-coordinate of the ball (column index)
- * @return True if a path is found to (6,5), otherwise false
+ * @param map the 2D array representing the maze (0 = open, non-zero = blocked)
+ * @param startRow the starting row
+ * @param startColumn the starting column
+ * @param goalRow the goal row
+ * @param goalColumn the goal column
+ * @return the solved maze with paths marked, or null if no solution exists
+ * @throws IllegalArgumentException if the maze is null, empty, not rectangular,
+ * or a coordinate is outside the maze
*/
- private static boolean setWay(int[][] map, int i, int j) {
- if (map[6][5] == 2) {
- return true;
+ public static int[][] solveMazeUsingFirstStrategy(int[][] map, int startRow, int startColumn, int goalRow, int goalColumn) {
+ validateCoordinates(map, startRow, startColumn, goalRow, goalColumn);
+ return solve(map, startRow, startColumn, goalRow, goalColumn, FIRST_STRATEGY_DIRECTIONS) ? map : null;
+ }
+
+ /**
+ * Solves the maze using the "up -> right -> down -> left" movement strategy.
+ *
+ * @param map the 2D array representing the maze (0 = open, non-zero = blocked)
+ * @param startRow the starting row
+ * @param startColumn the starting column
+ * @param goalRow the goal row
+ * @param goalColumn the goal column
+ * @return the solved maze with paths marked, or null if no solution exists
+ * @throws IllegalArgumentException if the maze is null, empty, not rectangular,
+ * or a coordinate is outside the maze
+ */
+ public static int[][] solveMazeUsingSecondStrategy(int[][] map, int startRow, int startColumn, int goalRow, int goalColumn) {
+ validateCoordinates(map, startRow, startColumn, goalRow, goalColumn);
+ return solve(map, startRow, startColumn, goalRow, goalColumn, SECOND_STRATEGY_DIRECTIONS) ? map : null;
+ }
+
+ private static boolean solve(int[][] map, int row, int column, int goalRow, int goalColumn, int[][] directions) {
+ if (!isInBounds(map, row, column) || map[row][column] != 0) {
+ return false;
}
- // If the current position is unvisited (0), explore it
- if (map[i][j] == 0) {
- // Mark the current position as '2'
- map[i][j] = 2;
+ map[row][column] = 2;
+ if (row == goalRow && column == goalColumn) {
+ return true;
+ }
- // Move down
- if (setWay(map, i + 1, j)) {
- return true;
- }
- // Move right
- else if (setWay(map, i, j + 1)) {
- return true;
- }
- // Move up
- else if (setWay(map, i - 1, j)) {
- return true;
- }
- // Move left
- else if (setWay(map, i, j - 1)) {
+ for (int[] direction : directions) {
+ if (solve(map, row + direction[0], column + direction[1], goalRow, goalColumn, directions)) {
return true;
}
-
- map[i][j] = 3; // Mark as dead end (3) if no direction worked
- return false;
}
+
+ map[row][column] = 3;
return false;
}
- /**
- * Attempts to find a path through the maze using an alternative movement
- * strategy "up -> right -> down -> left".
- *
- * @param map The 2D array representing the maze (walls, paths, etc.)
- * @param i The current x-coordinate of the ball (row index)
- * @param j The current y-coordinate of the ball (column index)
- * @return True if a path is found to (6,5), otherwise false
- */
- private static boolean setWay2(int[][] map, int i, int j) {
- if (map[6][5] == 2) {
- return true;
+ private static int validateMaze(int[][] map) {
+ if (map == null || map.length == 0 || map[0] == null || map[0].length == 0) {
+ throw new IllegalArgumentException("Maze must not be null or empty.");
}
- if (map[i][j] == 0) {
- map[i][j] = 2;
-
- // Move up
- if (setWay2(map, i - 1, j)) {
- return true;
- }
- // Move right
- else if (setWay2(map, i, j + 1)) {
- return true;
- }
- // Move down
- else if (setWay2(map, i + 1, j)) {
- return true;
- }
- // Move left
- else if (setWay2(map, i, j - 1)) {
- return true;
+ int columnCount = map[0].length;
+ for (int[] row : map) {
+ if (row == null || row.length != columnCount) {
+ throw new IllegalArgumentException("Maze must be a non-empty rectangular matrix.");
}
+ }
+ return columnCount;
+ }
- map[i][j] = 3; // Mark as dead end (3) if no direction worked
- return false;
+ private static void validateCoordinates(int[][] map, int startRow, int startColumn, int goalRow, int goalColumn) {
+ int columnCount = validateMaze(map);
+ if (startRow < 0 || startRow >= map.length || startColumn < 0 || startColumn >= columnCount || goalRow < 0 || goalRow >= map.length || goalColumn < 0 || goalColumn >= columnCount) {
+ throw new IllegalArgumentException("Start and goal coordinates must be inside the maze.");
}
- return false;
+ }
+
+ private static boolean isInBounds(int[][] map, int row, int column) {
+ return row >= 0 && row < map.length && column >= 0 && column < map[row].length;
}
}
diff --git a/src/main/java/com/thealgorithms/ciphers/ChaCha20.java b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java
new file mode 100644
index 000000000000..5f9906d406d4
--- /dev/null
+++ b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java
@@ -0,0 +1,136 @@
+package com.thealgorithms.ciphers;
+
+import java.util.Objects;
+
+/**
+ * Implements the ChaCha20 stream cipher described in RFC 8439.
+ *
+ *
This implementation is intended for educational purposes and should not
+ * be used as a replacement for a vetted cryptographic library in production.
+ *
+ * @see RFC 8439
+ */
+public final class ChaCha20 {
+
+ private static final int BLOCK_SIZE = 64;
+ private static final long MAX_COUNTER = 0xFFFF_FFFFL;
+ private static final int[] CONSTANTS = {0x61707865, 0x3320646e, 0x79622d32, 0x6b206574};
+
+ private ChaCha20() {
+ // Utility class
+ }
+
+ /**
+ * Encrypts bytes with ChaCha20. Decryption uses the same operation.
+ *
+ * @param input plaintext bytes; must not be {@code null}
+ * @param key 32-byte key
+ * @param nonce 12-byte nonce
+ * @param initialCounter unsigned 32-bit initial block counter
+ * @return encrypted bytes
+ * @throws NullPointerException if an argument is {@code null}
+ * @throws IllegalArgumentException if a key, nonce, or counter is invalid,
+ * or the counter would overflow while processing the input
+ */
+ public static byte[] encrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) {
+ validateInputs(input, key, nonce, initialCounter);
+
+ long blockCount = (input.length + (long) BLOCK_SIZE - 1) / BLOCK_SIZE;
+ if (blockCount > 0 && initialCounter > MAX_COUNTER - (blockCount - 1)) {
+ throw new IllegalArgumentException("Counter would overflow");
+ }
+
+ byte[] output = new byte[input.length];
+ for (int offset = 0; offset < input.length; offset += BLOCK_SIZE) {
+ long counter = initialCounter + offset / BLOCK_SIZE;
+ byte[] keyStream = block(key, nonce, counter);
+ int bytesToProcess = Math.min(BLOCK_SIZE, input.length - offset);
+
+ for (int i = 0; i < bytesToProcess; i++) {
+ output[offset + i] = (byte) (input[offset + i] ^ keyStream[i]);
+ }
+ }
+ return output;
+ }
+
+ /**
+ * Decrypts bytes with ChaCha20. This is identical to encryption.
+ *
+ * @param input ciphertext bytes; must not be {@code null}
+ * @param key 32-byte key
+ * @param nonce 12-byte nonce
+ * @param initialCounter unsigned 32-bit initial block counter
+ * @return decrypted bytes
+ */
+ public static byte[] decrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) {
+ return encrypt(input, key, nonce, initialCounter);
+ }
+
+ private static void validateInputs(byte[] input, byte[] key, byte[] nonce, long counter) {
+ Objects.requireNonNull(input, "input must not be null");
+ Objects.requireNonNull(key, "key must not be null");
+ Objects.requireNonNull(nonce, "nonce must not be null");
+
+ if (key.length != 32) {
+ throw new IllegalArgumentException("Key must be 32 bytes");
+ }
+ if (nonce.length != 12) {
+ throw new IllegalArgumentException("Nonce must be 12 bytes");
+ }
+ if (counter < 0 || counter > MAX_COUNTER) {
+ throw new IllegalArgumentException("Counter must be an unsigned 32-bit value");
+ }
+ }
+
+ private static byte[] block(byte[] key, byte[] nonce, long counter) {
+ int[] state = new int[16];
+ System.arraycopy(CONSTANTS, 0, state, 0, CONSTANTS.length);
+
+ for (int i = 0; i < 8; i++) {
+ state[4 + i] = littleEndianInt(key, i * 4);
+ }
+
+ state[12] = (int) counter;
+ state[13] = littleEndianInt(nonce, 0);
+ state[14] = littleEndianInt(nonce, 4);
+ state[15] = littleEndianInt(nonce, 8);
+
+ int[] workingState = state.clone();
+ for (int i = 0; i < 10; i++) {
+ quarterRound(workingState, 0, 4, 8, 12);
+ quarterRound(workingState, 1, 5, 9, 13);
+ quarterRound(workingState, 2, 6, 10, 14);
+ quarterRound(workingState, 3, 7, 11, 15);
+
+ quarterRound(workingState, 0, 5, 10, 15);
+ quarterRound(workingState, 1, 6, 11, 12);
+ quarterRound(workingState, 2, 7, 8, 13);
+ quarterRound(workingState, 3, 4, 9, 14);
+ }
+
+ byte[] output = new byte[BLOCK_SIZE];
+ for (int i = 0; i < workingState.length; i++) {
+ int word = workingState[i] + state[i];
+ output[i * 4] = (byte) word;
+ output[i * 4 + 1] = (byte) (word >>> 8);
+ output[i * 4 + 2] = (byte) (word >>> 16);
+ output[i * 4 + 3] = (byte) (word >>> 24);
+ }
+ return output;
+ }
+
+ static void quarterRound(int[] state, int a, int b, int c, int d) {
+ state[a] += state[b];
+ state[d] = Integer.rotateLeft(state[d] ^ state[a], 16);
+ state[c] += state[d];
+ state[b] = Integer.rotateLeft(state[b] ^ state[c], 12);
+ state[a] += state[b];
+ state[d] = Integer.rotateLeft(state[d] ^ state[a], 8);
+ state[c] += state[d];
+ state[b] = Integer.rotateLeft(state[b] ^ state[c], 7);
+ }
+
+ private static int littleEndianInt(byte[] bytes, int offset) {
+ return (bytes[offset] & 0xFF) | ((bytes[offset + 1] & 0xFF) << 8) | ((bytes[offset + 2] & 0xFF) << 16) | ((bytes[offset + 3] & 0xFF) << 24);
+ }
+}
diff --git a/src/main/java/com/thealgorithms/conversions/HexToOct.java b/src/main/java/com/thealgorithms/conversions/HexToOct.java
index d3a672d37424..ef696d305ee4 100644
--- a/src/main/java/com/thealgorithms/conversions/HexToOct.java
+++ b/src/main/java/com/thealgorithms/conversions/HexToOct.java
@@ -14,6 +14,7 @@ private HexToOct() {
*
* @param hex The Hexadecimal number as a String.
* @return The Decimal equivalent as an integer.
+ * @throws IllegalArgumentException if the string contains a character that is not a hexadecimal digit
*/
public static int hexToDecimal(String hex) {
String hexDigits = "0123456789ABCDEF";
@@ -23,6 +24,9 @@ public static int hexToDecimal(String hex) {
for (int i = 0; i < hex.length(); i++) {
char hexChar = hex.charAt(i);
int digitValue = hexDigits.indexOf(hexChar);
+ if (digitValue == -1) {
+ throw new IllegalArgumentException("Invalid hexadecimal digit: " + hexChar);
+ }
decimalValue = 16 * decimalValue + digitValue;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
index 0b4fcd91483c..7e03ca3856b5 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java
@@ -121,6 +121,9 @@ public void remove(E e) {
current = next;
}
}
+ if (layer < 0) {
+ return; // not found, nothing to unlink
+ }
for (int i = 0; i <= layer; i++) {
current.previous(i).setNext(i, current.next(i));
if (current.next(i) != null) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java
new file mode 100644
index 000000000000..6bb965aad4d6
--- /dev/null
+++ b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java
@@ -0,0 +1,56 @@
+package com.thealgorithms.datastructures.trees;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Queue;
+
+/**
+ * Given the root of a binary tree, returns the values of the nodes visible
+ * from the right side (the last node of each level in a level-order traversal).
+ *
+ *
Time complexity: O(n), Space complexity: O(n)
+ *
+ * @see LeetCode #199
+ */
+public final class RightSideViewOfBinaryTree {
+ private RightSideViewOfBinaryTree() {
+ }
+
+ public static List rightSideView(BinaryTree.Node root) {
+ List result = new ArrayList<>();
+ if (root == null) {
+ return result;
+ }
+
+ Queue queue = new LinkedList<>();
+ queue.add(root);
+
+ while (!queue.isEmpty()) {
+ int levelSize = queue.size();
+ for (int i = 0; i < levelSize; i++) {
+ BinaryTree.Node node = queue.poll();
+ if (i == levelSize - 1) {
+ result.add(node.data);
+ }
+ if (node.left != null) {
+ queue.add(node.left);
+ }
+ if (node.right != null) {
+ queue.add(node.right);
+ }
+ }
+ }
+ return result;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
index d01066f611bd..b21beafba746 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
@@ -21,8 +21,16 @@ private CatalanNumber() {
* n > 50, BigInteger class should be used instead long
*
* @return catalanArray[n] the nth Catalan number
+ * @throws IllegalArgumentException if n is negative
*/
static long findNthCatalan(int n) {
+ if (n < 0) {
+ throw new IllegalArgumentException("n must be non-negative");
+ }
+ if (n <= 1) {
+ return 1;
+ }
+
// Array to store the results of subproblems i.e Catalan numbers from [1...n-1]
long[] catalanArray = new long[n + 1];
diff --git a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
index 1de39adbc18a..a7caf7efa44f 100644
--- a/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
+++ b/src/main/java/com/thealgorithms/maths/BinomialCoefficient.java
@@ -21,9 +21,14 @@ private BinomialCoefficient() {
* @param numberOfObjects Number of objects to be chosen from total_objects
* @return number of ways in which no_of_objects objects can be chosen from total_objects
* objects
+ * @throws IllegalArgumentException if totalObjects or numberOfObjects is negative
*/
public static int binomialCoefficient(int totalObjects, int numberOfObjects) {
+ if (totalObjects < 0 || numberOfObjects < 0) {
+ throw new IllegalArgumentException("Arguments must be non-negative.");
+ }
+
// Base Case
if (numberOfObjects > totalObjects) {
return 0;
diff --git a/src/main/java/com/thealgorithms/maths/CatalanNumbers.java b/src/main/java/com/thealgorithms/maths/CatalanNumbers.java
index 387756bdfa0c..2f304d1c2b3c 100644
--- a/src/main/java/com/thealgorithms/maths/CatalanNumbers.java
+++ b/src/main/java/com/thealgorithms/maths/CatalanNumbers.java
@@ -1,38 +1,43 @@
package com.thealgorithms.maths;
+import java.math.BigInteger;
+
/**
* Calculate Catalan Numbers
*/
public final class CatalanNumbers {
+ private static final int MAX_SUPPORTED_INDEX = 35;
+
private CatalanNumbers() {
}
/**
- * Calculate the nth Catalan number using a recursive formula.
+ * Calculate the nth Catalan number using the factorial formula.
*
* @param n the index of the Catalan number to compute
* @return the nth Catalan number
+ * @throws IllegalArgumentException if n is negative or exceeds the maximum supported index for long
*/
public static long catalan(final int n) {
if (n < 0) {
throw new IllegalArgumentException("Index must be non-negative");
}
- return factorial(2 * n) / (factorial(n + 1) * factorial(n));
+ if (n > MAX_SUPPORTED_INDEX) {
+ throw new IllegalArgumentException("Index exceeds maximum supported value for long");
+ }
+ return factorial(2 * n).divide(factorial(n + 1).multiply(factorial(n))).longValueExact();
}
/**
- * Calculate the factorial of a number.
+ * Calculate the factorial of a number using BigInteger to prevent integer overflow.
*
* @param n the number to compute the factorial for
- * @return the factorial of n
+ * @return the factorial of n as BigInteger
*/
- private static long factorial(final int n) {
- if (n == 0 || n == 1) {
- return 1;
- }
- long result = 1;
+ private static BigInteger factorial(final int n) {
+ BigInteger result = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
- result *= i;
+ result = result.multiply(BigInteger.valueOf(i));
}
return result;
}
diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
index f7e2c7629551..b6c09c2cdb82 100644
--- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java
+++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java
@@ -6,7 +6,7 @@ private DistanceFormula() {
public static double euclideanDistance(double x1, double y1, double x2, double y2) {
double dX = Math.pow(x2 - x1, 2);
- double dY = Math.pow(y2 - x1, 2);
+ double dY = Math.pow(y2 - y1, 2);
return Math.sqrt(dX + dY);
}
diff --git a/src/main/java/com/thealgorithms/maths/Pow.java b/src/main/java/com/thealgorithms/maths/Pow.java
index 377b37ac4569..33dda5ba2ddc 100644
--- a/src/main/java/com/thealgorithms/maths/Pow.java
+++ b/src/main/java/com/thealgorithms/maths/Pow.java
@@ -22,6 +22,7 @@ private Pow() {
* @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer.
* @return the result of {@code a}{@code b} as a {@code long}.
* @throws IllegalArgumentException if {@code b} is negative.
+ * @throws ArithmeticException if the result overflows a {@code long}.
*/
public static long pow(int a, int b) {
if (b < 0) {
@@ -29,7 +30,7 @@ public static long pow(int a, int b) {
}
long result = 1;
for (int i = 1; i <= b; i++) {
- result *= a;
+ result = Math.multiplyExact(result, (long) a);
}
return result;
}
diff --git a/src/main/java/com/thealgorithms/maths/SmithNumber.java b/src/main/java/com/thealgorithms/maths/SmithNumber.java
index c06e0023d9bb..41d7bebed257 100644
--- a/src/main/java/com/thealgorithms/maths/SmithNumber.java
+++ b/src/main/java/com/thealgorithms/maths/SmithNumber.java
@@ -18,10 +18,9 @@ private SmithNumber() {
private static int primeFactorDigitSum(int n) {
int sum = 0;
- int num = n;
// Factorize the number using trial division
- for (int i = 2; i * i <= num; i++) {
+ for (int i = 2; (long) i * i <= n; i++) {
while (n % i == 0) { // while i divides n
sum += SumOfDigits.sumOfDigits(i); // add sum of digits of factor
n /= i; // divide n by the factor
@@ -43,7 +42,7 @@ private static int primeFactorDigitSum(int n) {
* @return {@code true} if {@code number} is a Smith number, otherwise false
*/
public static boolean isSmithNumber(int number) {
- if (PrimeCheck.isPrime(number)) {
+ if (number <= 3 || PrimeCheck.isPrime(number)) {
return false; // Smith numbers must be composite
}
diff --git a/src/main/java/com/thealgorithms/misc/MoveZeroes.java b/src/main/java/com/thealgorithms/misc/MoveZeroes.java
new file mode 100644
index 000000000000..31d6eb8dad98
--- /dev/null
+++ b/src/main/java/com/thealgorithms/misc/MoveZeroes.java
@@ -0,0 +1,28 @@
+package com.thealgorithms.misc;
+
+/**
+ * Moves all zeroes in an array to the end while maintaining the relative
+ * order of non-zero elements. The operation is performed in-place.
+ *
+ *
Time complexity: O(n), Space complexity: O(1)
+ *
+ * @see LeetCode #283
+ */
+public final class MoveZeroes {
+ private MoveZeroes() {
+ }
+
+ public static void moveZeroes(int[] nums) {
+ int insertPos = 0;
+ for (int num : nums) {
+ if (num != 0) {
+ nums[insertPos++] = num;
+ }
+ }
+ while (insertPos < nums.length) {
+ nums[insertPos++] = 0;
+ }
+ }
+}
diff --git a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
index aa938447b864..317db0dead05 100644
--- a/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
+++ b/src/main/java/com/thealgorithms/searches/BinarySearch2dArray.java
@@ -28,13 +28,13 @@ private BinarySearch2dArray() {
* @return An array containing the row and column indices of the target, or [-1,
* -1] if the target is not found.
*/
- static int[] binarySearch(int[][] arr, int target) {
+ public static int[] binarySearch(int[][] arr, int target) {
int rowCount = arr.length;
int colCount = arr[0].length;
// Edge case: If there's only one row, search that row directly.
if (rowCount == 1) {
- return binarySearch(arr, target, 0, 0, colCount);
+ return binarySearch(arr, target, 0, 0, colCount - 1);
}
// Set initial boundaries for binary search on rows.
@@ -70,6 +70,11 @@ else if (arr[midRow][midCol] < target) {
return new int[] {endRow, midCol};
}
+ // Edge case: If there is only one column, target cannot be outside midCol.
+ if (colCount == 1) {
+ return new int[] {-1, -1};
+ }
+
// If target is smaller than the element in the left of startRow, perform a
// binary search on the left of startRow.
if (target <= arr[startRow][midCol - 1]) {
diff --git a/src/main/java/com/thealgorithms/searches/BoyerMoore.java b/src/main/java/com/thealgorithms/searches/BoyerMoore.java
index 6998021503cc..5c491210302b 100644
--- a/src/main/java/com/thealgorithms/searches/BoyerMoore.java
+++ b/src/main/java/com/thealgorithms/searches/BoyerMoore.java
@@ -1,5 +1,8 @@
package com.thealgorithms.searches;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Boyer-Moore string search algorithm.
* Efficient algorithm for substring search.
@@ -7,21 +10,16 @@
*/
public class BoyerMoore {
- private final int radix; // Radix (number of possible characters)
- private final int[] right; // Bad character rule table
+ private final Map right; // Bad character rule table: last index of each pattern character
private final String pattern;
public BoyerMoore(String pat) {
this.pattern = pat;
- this.radix = 256;
- this.right = new int[radix];
-
- for (int c = 0; c < radix; c++) {
- right[c] = -1;
- }
+ // A map instead of a 256-entry array, so characters outside extended ASCII work too
+ this.right = new HashMap<>();
for (int j = 0; j < pat.length(); j++) {
- right[pat.charAt(j)] = j;
+ right.put(pat.charAt(j), j);
}
}
@@ -40,7 +38,7 @@ public int search(String text) {
char txtChar = text.charAt(i + j);
char patChar = pattern.charAt(j);
if (patChar != txtChar) {
- skip = Math.max(1, j - right[txtChar]);
+ skip = Math.max(1, j - right.getOrDefault(txtChar, -1));
break;
}
}
diff --git a/src/main/java/com/thealgorithms/searches/ExponentialSearch.java b/src/main/java/com/thealgorithms/searches/ExponentialSearch.java
index e666b9148aaa..9405f5995687 100644
--- a/src/main/java/com/thealgorithms/searches/ExponentialSearch.java
+++ b/src/main/java/com/thealgorithms/searches/ExponentialSearch.java
@@ -19,7 +19,7 @@
* Note: This algorithm requires that the input array be sorted.
*
*/
-class ExponentialSearch implements SearchAlgorithm {
+public final class ExponentialSearch implements SearchAlgorithm {
/**
* Finds the index of the specified key in a sorted array using exponential search.
@@ -31,13 +31,13 @@ class ExponentialSearch implements SearchAlgorithm {
*/
@Override
public > int find(T[] array, T key) {
- if (array.length == 0) {
+ if (array == null || array.length == 0 || key == null) {
return -1;
}
- if (array[0].equals(key)) {
+ if (key.compareTo(array[0]) == 0) {
return 0;
}
- if (array[array.length - 1].equals(key)) {
+ if (key.compareTo(array[array.length - 1]) == 0) {
return array.length - 1;
}
diff --git a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java
index fa91cd14a1af..4db6874f0c08 100644
--- a/src/main/java/com/thealgorithms/searches/FibonacciSearch.java
+++ b/src/main/java/com/thealgorithms/searches/FibonacciSearch.java
@@ -15,8 +15,7 @@
* Note: This algorithm requires that the input array be sorted.
*
*/
-@SuppressWarnings({"rawtypes", "unchecked"})
-public class FibonacciSearch implements SearchAlgorithm {
+public final class FibonacciSearch implements SearchAlgorithm {
/**
* Finds the index of the specified key in a sorted array using Fibonacci search.
@@ -24,11 +23,14 @@ public class FibonacciSearch implements SearchAlgorithm {
* @param array The sorted array to search.
* @param key The element to search for.
* @param The type of the elements in the array, which must be comparable.
- * @throws IllegalArgumentException if the input array is not sorted or empty, or if the key is null.
+ * @throws IllegalArgumentException if the input array is null, not sorted or empty, or if the key is null.
* @return The index of the key if found, otherwise -1.
*/
@Override
public > int find(T[] array, T key) {
+ if (array == null) {
+ throw new IllegalArgumentException("Input array must not be null.");
+ }
if (array.length == 0) {
throw new IllegalArgumentException("Input array must not be empty.");
}
@@ -76,7 +78,7 @@ public > int find(T[] array, T key) {
return -1;
}
- private boolean isSorted(Comparable[] array) {
+ private > boolean isSorted(T[] array) {
for (int i = 1; i < array.length; i++) {
if (array[i - 1].compareTo(array[i]) > 0) {
return false;
diff --git a/src/main/java/com/thealgorithms/searches/JumpSearch.java b/src/main/java/com/thealgorithms/searches/JumpSearch.java
index 4253f4182db1..5e4c6da15f86 100644
--- a/src/main/java/com/thealgorithms/searches/JumpSearch.java
+++ b/src/main/java/com/thealgorithms/searches/JumpSearch.java
@@ -56,7 +56,7 @@
* @see BinarySearch
* @see LinearSearch
*/
-public class JumpSearch implements SearchAlgorithm {
+public final class JumpSearch implements SearchAlgorithm {
/**
* Jump Search algorithm implementation.
@@ -67,6 +67,10 @@ public class JumpSearch implements SearchAlgorithm {
*/
@Override
public > int find(T[] array, T key) {
+ if (array == null || array.length == 0 || key == null) {
+ return -1;
+ }
+
int length = array.length;
int blockSize = (int) Math.sqrt(length);
@@ -78,7 +82,7 @@ public > int find(T[] array, T key) {
// Perform linear search within the identified block
for (int i = limit - blockSize; i <= limit && i < length; i++) {
- if (array[i].equals(key)) {
+ if (array[i] != null && key.compareTo(array[i]) == 0) {
return i;
}
}
diff --git a/src/main/java/com/thealgorithms/searches/LinearSearch.java b/src/main/java/com/thealgorithms/searches/LinearSearch.java
index c5f6e6ba9776..3ec1768916e5 100644
--- a/src/main/java/com/thealgorithms/searches/LinearSearch.java
+++ b/src/main/java/com/thealgorithms/searches/LinearSearch.java
@@ -54,7 +54,8 @@ public class LinearSearch implements SearchAlgorithm {
*
* @param array List to be searched (can be unsorted)
* @param value Key being searched for
- * @return Location of the key, -1 if array is null or empty, or key not found
+ * @return the index of the matching element, or -1 if the array is null or empty,
+ * the value is null, or no matching element is found; null array elements are skipped
*/
@Override
public > int find(T[] array, T value) {
diff --git a/src/main/java/com/thealgorithms/searches/LowerBound.java b/src/main/java/com/thealgorithms/searches/LowerBound.java
index 5a1401edd3c2..7325082c223b 100644
--- a/src/main/java/com/thealgorithms/searches/LowerBound.java
+++ b/src/main/java/com/thealgorithms/searches/LowerBound.java
@@ -13,7 +13,7 @@
* This is an extension of BinarySearch.
*
*
- * Worst-case performance O(log n) Best-case performance O(1) Average
+ * Worst-case performance O(log n) Best-case performance O(log n) Average
* performance O(log n) Worst-case space complexity O(1)
*
* @author Pratik Padalia (https://github.com/15pratik)
@@ -26,10 +26,13 @@ class LowerBound implements SearchAlgorithm {
* @param array is an array where the LowerBound value is to be found
* @param key is an element for which the LowerBound is to be found
* @param is any comparable type
- * @return index of the LowerBound element
+ * @return index of the first element not less than key, or 0 if array is null/empty or key is null
*/
@Override
public > int find(T[] array, T key) {
+ if (array == null || array.length == 0 || key == null) {
+ return 0;
+ }
return search(array, key, 0, array.length - 1);
}
@@ -51,10 +54,8 @@ private > int search(T[] array, T key, int left, int rig
int median = (left + right) >>> 1;
int comp = key.compareTo(array[median]);
- if (comp == 0) {
- return median;
- } else if (comp < 0) {
- // median position can be a possible solution
+ if (comp <= 0) {
+ // key is less than or equal to array[median], median position can be a possible solution
return search(array, key, left, median);
} else {
// key we are looking is greater, so we must look on the right of median position
diff --git a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
index 81e16dbbbf07..35d696f2a2f2 100644
--- a/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
+++ b/src/main/java/com/thealgorithms/searches/RabinKarpAlgorithm.java
@@ -13,9 +13,14 @@ public static int search(String pattern, String text, int primeNumber) {
int index = -1; // -1 here represents not found
int patternLength = pattern.length();
int textLength = text.length();
- int hashForPattern = 0;
- int hashForText = 0;
- int h = 1;
+ if (patternLength > textLength) {
+ return index;
+ }
+
+ // long, so hash * ALPHABET_SIZE cannot overflow for large primes such as 1_000_000_007
+ long hashForPattern = 0;
+ long hashForText = 0;
+ long h = 1;
// The value of h would be "pow(d, patternLength-1)%primeNumber"
for (int i = 0; i < patternLength - 1; i++) {
diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
index ecdcd36adf21..4b66cf2a220e 100644
--- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java
@@ -20,7 +20,7 @@
* doesn't exist in the array, an array
* {-1, -1} will be returned.
*/
-public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm {
+public final class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm {
@Override
public > int[] find(T[][] matrix, T key) {
@@ -28,6 +28,10 @@ public > int[] find(T[][] matrix, T key) {
}
public static > int[] search(T[][] matrix, T target) {
+ if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0 || target == null) {
+ return new int[] {-1, -1};
+ }
+
int rowPointer = 0; // The pointer at 0th row
int colPointer = matrix[0].length - 1; // The pointer at end column
diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
index 192c4d26c735..9455636a4c9c 100644
--- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
+++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java
@@ -19,24 +19,39 @@ private SaddlebackSearch() {
}
/**
- * This method performs Saddleback Search
+ * Searches for a key in a row-wise and column-wise sorted 2D array starting from the bottom-left corner.
+ *
+ * @param arr The sorted matrix.
+ * @param key The element to search for.
+ * @throws IllegalArgumentException if the array is null or empty.
+ * @return The index (row and column) of the element if found. Else returns {-1, -1}.
+ */
+ public static int[] find(int[][] arr, int key) {
+ if (arr == null || arr.length == 0) {
+ throw new IllegalArgumentException("Array is empty");
+ }
+ return find(arr, arr.length - 1, 0, key);
+ }
+
+ /**
+ * This method performs Saddleback Search starting from the specified row and column.
*
* @param arr The **Sorted** array in which we will search the element.
* @param row the current row.
* @param col the current column.
* @param key the element that we want to search for.
- * @throws IllegalArgumentException if the array is empty.
+ * @throws IllegalArgumentException if the array is null or empty.
* @return The index(row and column) of the element if found. Else returns
* -1 -1.
*/
- static int[] find(int[][] arr, int row, int col, int key) {
- if (arr.length == 0) {
+ public static int[] find(int[][] arr, int row, int col, int key) {
+ if (arr == null || arr.length == 0) {
throw new IllegalArgumentException("Array is empty");
}
// array to store the answer row and column
int[] ans = {-1, -1};
- if (row < 0 || col >= arr[row].length) {
+ if (row < 0 || row >= arr.length || arr[row] == null || col < 0 || col >= arr[row].length) {
return ans;
}
if (arr[row][col] == key) {
diff --git a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java
index b53c7e5256ca..20a07adafd26 100644
--- a/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java
+++ b/src/main/java/com/thealgorithms/searches/SearchInARowAndColWiseSortedMatrix.java
@@ -1,32 +1,42 @@
-package com.thealgorithms.searches;
-
-public class SearchInARowAndColWiseSortedMatrix {
- /**
- * Search a key in row and column wise sorted matrix
- *
- * @param matrix matrix to be searched
- * @param value Key being searched for
- * @author Sadiul Hakim : https://github.com/sadiul-hakim
- */
- public int[] search(int[][] matrix, int value) {
- int n = matrix.length;
- // This variable iterates over rows
- int i = 0;
- // This variable iterates over columns
- int j = n - 1;
- int[] result = {-1, -1};
- while (i < n && j >= 0) {
- if (matrix[i][j] == value) {
- result[0] = i;
- result[1] = j;
- return result;
- }
- if (value > matrix[i][j]) {
- i++;
- } else {
- j--;
- }
- }
- return result;
- }
-}
+package com.thealgorithms.searches;
+
+public final class SearchInARowAndColWiseSortedMatrix {
+ /**
+ * Search a key in row and column wise sorted matrix
+ *
+ * @param matrix matrix to be searched
+ * @param value Key being searched for
+ * @return row and column indices if found, otherwise {-1, -1}
+ * @author Sadiul Hakim : https://github.com/sadiul-hakim
+ */
+ public int[] search(int[][] matrix, int value) {
+ if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
+ return new int[] {-1, -1};
+ }
+
+ int rows = matrix.length;
+ int cols = matrix[0].length;
+ // This variable iterates over rows
+ int i = 0;
+ // This variable iterates over columns, starting from top-right corner
+ int j = cols - 1;
+ int[] result = {-1, -1};
+ while (i < rows && j >= 0) {
+ if (matrix[i] == null || j >= matrix[i].length) {
+ i++;
+ continue;
+ }
+ if (matrix[i][j] == value) {
+ result[0] = i;
+ result[1] = j;
+ return result;
+ }
+ if (value > matrix[i][j]) {
+ i++;
+ } else {
+ j--;
+ }
+ }
+ return result;
+ }
+}
diff --git a/src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java b/src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java
index 473fc2c3f094..eb32669d1741 100644
--- a/src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java
+++ b/src/main/java/com/thealgorithms/searches/SentinelLinearSearch.java
@@ -33,7 +33,7 @@
* @see LinearSearch
* @see SearchAlgorithm
*/
-public class SentinelLinearSearch implements SearchAlgorithm {
+public final class SentinelLinearSearch implements SearchAlgorithm {
/**
* Performs sentinel linear search on the given array.
*
@@ -65,8 +65,8 @@ public > int find(T[] array, T key) {
int i = 0;
// Search without bound checking since sentinel guarantees we'll find the key
- // Null check for array element to prevent NPE when array contains null elements
- while (array[i] != null && array[i].compareTo(key) != 0) {
+ // Null check for array element to skip nulls and prevent NPE when array contains null elements
+ while (array[i] == null || array[i].compareTo(key) != 0) {
i++;
}
diff --git a/src/main/java/com/thealgorithms/searches/TernarySearch.java b/src/main/java/com/thealgorithms/searches/TernarySearch.java
index 4d9f55ea9917..1071d172ef21 100644
--- a/src/main/java/com/thealgorithms/searches/TernarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/TernarySearch.java
@@ -3,38 +3,44 @@
import com.thealgorithms.devutils.searches.SearchAlgorithm;
/**
- * A ternary search algorithm is a technique in computer science for finding the
- * minimum or maximum of a unimodal function The algorithm determines either
- * that the minimum or maximum cannot be in the first third of the domain or
- * that it cannot be in the last third of the domain, then repeats on the
- * remaining third.
+ * A ternary search algorithm is a divide-and-conquer algorithm that searches for
+ * a key in a sorted array by dividing the search domain into three parts.
*
*
- * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average
- * performance Θ(log3(N)) Worst-case space complexity O(1)
+ * Worst-case performance: Θ(log3(N))
+ * Best-case performance: O(1)
+ * Average performance: Θ(log3(N))
+ * Worst-case space complexity: O(log3(N))
*
* @author Podshivalov Nikita (https://github.com/nikitap492)
* @see SearchAlgorithm
* @see IterativeBinarySearch
*/
-public class TernarySearch implements SearchAlgorithm {
+public final class TernarySearch implements SearchAlgorithm {
/**
- * @param arr The **Sorted** array in which we will search the element.
+ * Searches for a value in a sorted array using ternary search.
+ *
+ * @param arr The sorted array in which we will search for the element.
* @param value The value that we want to search for.
- * @return The index of the element if found. Else returns -1.
+ * @return The index of the element if found. Returns -1 if the array is null or empty, if value is null, or if not found.
*/
@Override
public > int find(T[] arr, T value) {
+ if (arr == null || arr.length == 0 || value == null) {
+ return -1;
+ }
return ternarySearch(arr, value, 0, arr.length - 1);
}
/**
- * @param arr The **Sorted** array in which we will search the element.
+ * Recursively searches for the specified key within the range [start, end].
+ *
+ * @param arr The sorted array in which we will search the element.
* @param key The value that we want to search for.
- * @param start The starting index from which we will start Searching.
- * @param end The ending index till which we will Search.
- * @return Returns the index of the Element if found. Else returns -1.
+ * @param start The starting index from which we will start searching.
+ * @param end The ending index till which we will search.
+ * @return Returns the index of the element if found. Else returns -1.
*/
private > int ternarySearch(T[] arr, T key, int start, int end) {
if (start > end) {
@@ -45,16 +51,22 @@ private > int ternarySearch(T[] arr, T key, int start, i
/* Second boundary: add 2/3 of length to start */
int mid2 = start + 2 * (end - start) / 3;
- if (key.compareTo(arr[mid1]) == 0) {
+ int cmp1 = key.compareTo(arr[mid1]);
+ if (cmp1 == 0) {
return mid1;
- } else if (key.compareTo(arr[mid2]) == 0) {
+ }
+
+ int cmp2 = key.compareTo(arr[mid2]);
+ if (cmp2 == 0) {
return mid2;
- } /* Search the first (1/3) rd part of the array.*/ else if (key.compareTo(arr[mid1]) < 0) {
- return ternarySearch(arr, key, start, --mid1);
- } /* Search 3rd (1/3)rd part of the array */ else if (key.compareTo(arr[mid2]) > 0) {
- return ternarySearch(arr, key, ++mid2, end);
- } /* Search middle (1/3)rd part of the array */ else {
- return ternarySearch(arr, key, mid1, mid2);
+ }
+
+ if (cmp1 < 0) {
+ return ternarySearch(arr, key, start, mid1 - 1);
+ } else if (cmp2 > 0) {
+ return ternarySearch(arr, key, mid2 + 1, end);
+ } else {
+ return ternarySearch(arr, key, mid1 + 1, mid2 - 1);
}
}
}
diff --git a/src/main/java/com/thealgorithms/searches/UpperBound.java b/src/main/java/com/thealgorithms/searches/UpperBound.java
index ec52c7a0ae5c..5344f22994b1 100644
--- a/src/main/java/com/thealgorithms/searches/UpperBound.java
+++ b/src/main/java/com/thealgorithms/searches/UpperBound.java
@@ -13,7 +13,7 @@
* This is an extension of BinarySearch.
*
*
- * Worst-case performance O(log n) Best-case performance O(1) Average
+ * Worst-case performance O(log n) Best-case performance O(log n) Average
* performance O(log n) Worst-case space complexity O(1)
*
* @author Pratik Padalia (https://github.com/15pratik)
@@ -26,10 +26,13 @@ class UpperBound implements SearchAlgorithm {
* @param array is an array where the UpperBound value is to be found
* @param key is an element for which the UpperBound is to be found
* @param is any comparable type
- * @return index of the UpperBound element
+ * @return index of the first element greater than key, last index if no such element exists, or 0 if array is null/empty or key is null
*/
@Override
public > int find(T[] array, T key) {
+ if (array == null || array.length == 0 || key == null) {
+ return 0;
+ }
return search(array, key, 0, array.length - 1);
}
diff --git a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
index f7e12da06568..2e3a2fcea704 100644
--- a/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
+++ b/src/main/java/com/thealgorithms/sorts/DutchNationalFlagSort.java
@@ -13,6 +13,9 @@ public class DutchNationalFlagSort implements SortAlgorithm {
@Override
public > T[] sort(T[] array) {
+ if (array.length == 0) {
+ return array;
+ }
return dutchNationalFlagSort(array, array[(int) Math.ceil((array.length) / 2.0) - 1]);
}
diff --git a/src/main/java/com/thealgorithms/sorts/FlashSort.java b/src/main/java/com/thealgorithms/sorts/FlashSort.java
index e8dbf8c42742..79c2d8b82700 100644
--- a/src/main/java/com/thealgorithms/sorts/FlashSort.java
+++ b/src/main/java/com/thealgorithms/sorts/FlashSort.java
@@ -76,7 +76,8 @@ private > void flashSort(T[] arr) {
return; // All elements are the same
}
- final int m = (int) (classificationRatio * arr.length);
+ // At least one class, otherwise small arrays index into an empty classification table
+ final int m = Math.max(1, (int) (classificationRatio * arr.length));
final int[] classificationArray = new int[m];
diff --git a/src/main/java/com/thealgorithms/sorts/SwapSort.java b/src/main/java/com/thealgorithms/sorts/SwapSort.java
index b5c1c3892546..169fba93fc57 100644
--- a/src/main/java/com/thealgorithms/sorts/SwapSort.java
+++ b/src/main/java/com/thealgorithms/sorts/SwapSort.java
@@ -17,7 +17,12 @@ public > T[] sort(T[] array) {
final int amountSmallerElements = this.getSmallerElementCount(array, index);
if (amountSmallerElements > 0) {
- SortUtils.swap(array, index, index + amountSmallerElements);
+ int target = index + amountSmallerElements;
+ // Skip slots that already hold an equal element, otherwise two equal values swap forever
+ while (array[target].compareTo(array[index]) == 0) {
+ target++;
+ }
+ SortUtils.swap(array, index, target);
} else {
index++;
}
diff --git a/src/main/java/com/thealgorithms/sorts/TreeSort.java b/src/main/java/com/thealgorithms/sorts/TreeSort.java
index 6f4e5509489d..1c0b407c7f84 100644
--- a/src/main/java/com/thealgorithms/sorts/TreeSort.java
+++ b/src/main/java/com/thealgorithms/sorts/TreeSort.java
@@ -3,6 +3,8 @@
import static com.thealgorithms.sorts.SortUtils.print;
import com.thealgorithms.datastructures.trees.BSTRecursiveGeneric;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
/**
@@ -30,38 +32,39 @@ public > List sort(List unsortedList) {
}
private > T[] doTreeSortArray(T[] unsortedArray) {
- // create a generic BST tree
- BSTRecursiveGeneric tree = new BSTRecursiveGeneric();
-
- // add all elements to the tree
- for (T element : unsortedArray) {
- tree.add(element);
- }
-
- // get the sorted list by inorder traversal of the tree
- List sortedList = tree.inorderSort();
-
- // add the elements back to the initial array
- int i = 0;
- for (T element : sortedList) {
- unsortedArray[i++] = element;
- }
-
- // return the array
- return unsortedArray;
+ // sort through the list path and copy the result back into the initial array
+ List sortedList = doTreeSortList(Arrays.asList(unsortedArray));
+ return sortedList.toArray(unsortedArray);
}
private > List doTreeSortList(Iterable unsortedList) {
- // create a generic BST tree
- BSTRecursiveGeneric tree = new BSTRecursiveGeneric();
+ // the BST ignores duplicate keys, so pair every element with its position to keep equal values apart
+ BSTRecursiveGeneric> tree = new BSTRecursiveGeneric<>();
// add all elements to the tree
+ int position = 0;
for (T element : unsortedList) {
- tree.add(element);
+ tree.add(new Keyed<>(element, position++));
}
// get the sorted list by inorder traversal of the tree and return it
- return tree.inorderSort();
+ List sortedList = new ArrayList<>();
+ for (Keyed keyed : tree.inorderSort()) {
+ sortedList.add(keyed.value());
+ }
+ return sortedList;
+ }
+
+ /**
+ * An element plus its original position. Equal elements are ordered by position,
+ * which also makes the sort stable.
+ */
+ private record Keyed>(T value, int position) implements Comparable> {
+ @Override
+ public int compareTo(Keyed other) {
+ int byValue = value.compareTo(other.value);
+ return byValue != 0 ? byValue : Integer.compare(position, other.position);
+ }
}
public static void main(String[] args) {
diff --git a/src/main/java/com/thealgorithms/streaming/TDigest.java b/src/main/java/com/thealgorithms/streaming/TDigest.java
new file mode 100644
index 000000000000..b1c826b1857c
--- /dev/null
+++ b/src/main/java/com/thealgorithms/streaming/TDigest.java
@@ -0,0 +1,540 @@
+package com.thealgorithms.streaming;
+
+import java.util.Arrays;
+
+/**
+ * A t-digest: a small, mergeable sketch that answers any quantile of a stream, with
+ * much better accuracy at the tails than in the middle.
+ *
+ *
The sketch is a list of centroids, each holding a mean and a weight, kept sorted by mean.
+ * Together they approximate the distribution of everything ever added. What makes a t-digest more
+ * than a histogram is the rule that decides how big a centroid is allowed to be: instead of a fixed
+ * bucket width, the size limit is expressed through a scale function
+ *
+ *
and a centroid may absorb points only while it spans at most one unit of {@code k}. Because
+ * {@code asin} is steep near {@code q = 0} and {@code q = 1}, centroids near the tails are forced to
+ * stay tiny - often a single point - while centroids near the median are allowed to grow large.
+ * That is exactly the trade one wants in practice: the rank error is of the order of
+ * {@code 1 / compression} around the median and shrinks as {@code q} approaches 0 or 1, so
+ * {@code p99.9} comes out nearly exact. On smooth data the interpolation between centroids brings
+ * the error down by another order of magnitude, and the whole sketch still fits in a few kilobytes.
+ *
+ *
Insertions are buffered and folded into the centroid list in batches, which keeps the amortised
+ * cost per sample low. The minimum and the maximum are tracked separately and reported exactly.
+ *
+ *
+ *
Cost, with {@code d} the compression parameter
+ *
Operation
Complexity
+ *
{@link #add(double)}
O(log d) amortised
+ *
{@link #quantile(double)}, {@link #cdf(double)}
O(d)
+ *
{@link #merge(TDigest)}
O(d log d)
+ *
memory
O(d), independent of the stream length
+ *
+ *
+ *
Usage
+ *
+ *
{@code
+ * TDigest digest = new TDigest(100);
+ * for (double latency : latencies) {
+ * digest.add(latency);
+ * }
+ * digest.quantile(0.5); // median
+ * digest.quantile(0.999); // deep tail, the case t-digest is built for
+ * digest.cdf(250.0); // share of samples below 250
+ *
+ * // Sketches computed on different shards combine the way partial sums do.
+ * shardA.merge(shardB);
+ * }
+ *
+ *
Query methods fold the pending insertion buffer in before answering, so they mutate internal
+ * state; they are not safe to call concurrently. This class is not thread-safe.
+ *
+ * @see P2QuantileEstimator for a constant-memory estimator of one fixed quantile
+ * @see T. Dunning, O. Ertl, Computing extremely accurate quantiles using t-digests
+ */
+public final class TDigest {
+
+ /** Below roughly this value the scale function stops leaving room for a useful number of centroids. */
+ private static final double MIN_COMPRESSION = 10.0;
+
+ private static final double TWO_PI = 2.0 * Math.PI;
+
+ /** Buffered points per centroid slot; larger buffers mean fewer, bigger merge passes. */
+ private static final int BUFFER_FACTOR = 5;
+
+ /**
+ * How many centroid slots to reserve per unit of compression. Repeated merges make centroids
+ * atomic, so they pack less tightly than the scale function alone would suggest: in practice the
+ * sketch settles around {@code 0.6 * compression} centroids rather than the ideal
+ * {@code compression / 2}. Twice the compression leaves ample headroom.
+ */
+ private static final int CENTROID_SLOTS_PER_UNIT = 2;
+
+ /** Below this length the parallel sort switches to insertion sort. */
+ private static final int INSERTION_SORT_THRESHOLD = 16;
+
+ private final double compression;
+
+ private final double[] centroidMeans;
+ private final double[] centroidWeights;
+ private int centroidCount;
+
+ private final double[] bufferMeans;
+ private final double[] bufferWeights;
+ private int bufferCount;
+
+ private final double[] scratchMeans;
+ private final double[] scratchWeights;
+
+ private double totalWeight;
+ private double min = Double.POSITIVE_INFINITY;
+ private double max = Double.NEGATIVE_INFINITY;
+
+ /**
+ * Creates an empty digest with a compression of 100, a good default for most streams.
+ */
+ public TDigest() {
+ this(100.0);
+ }
+
+ /**
+ * Creates an empty digest.
+ *
+ * @param compression the size/accuracy trade-off; around {@code 0.6 * compression} centroids end
+ * up being kept, so larger values cost more memory and give smaller quantile errors
+ * @throws IllegalArgumentException if {@code compression} is smaller than 10 or not finite
+ */
+ public TDigest(double compression) {
+ if (!(compression >= MIN_COMPRESSION) || !Double.isFinite(compression)) {
+ throw new IllegalArgumentException("The compression must be finite and at least " + MIN_COMPRESSION + ", but was " + compression);
+ }
+ this.compression = compression;
+
+ int scale = (int) Math.ceil(compression) + 2;
+ int centroidCapacity = CENTROID_SLOTS_PER_UNIT * scale;
+ this.centroidMeans = new double[centroidCapacity];
+ this.centroidWeights = new double[centroidCapacity];
+
+ int bufferCapacity = BUFFER_FACTOR * scale;
+ this.bufferMeans = new double[bufferCapacity];
+ this.bufferWeights = new double[bufferCapacity];
+
+ this.scratchMeans = new double[centroidCapacity + bufferCapacity];
+ this.scratchWeights = new double[centroidCapacity + bufferCapacity];
+ }
+
+ /**
+ * Adds one sample of unit weight.
+ *
+ * @param value the sample to add
+ * @throws IllegalArgumentException if {@code value} is NaN or infinite
+ */
+ public void add(double value) {
+ add(value, 1.0);
+ }
+
+ /**
+ * Adds a sample that stands for several observations of the same value.
+ *
+ * @param value the sample to add
+ * @param weight how many observations the sample represents, strictly positive
+ * @throws IllegalArgumentException if {@code value} is not finite or {@code weight} is not strictly positive
+ */
+ public void add(double value, double weight) {
+ if (!Double.isFinite(value)) {
+ throw new IllegalArgumentException("Samples must be finite, but was " + value);
+ }
+ if (!(weight > 0.0) || !Double.isFinite(weight)) {
+ throw new IllegalArgumentException("The weight must be finite and positive, but was " + weight);
+ }
+ if (bufferCount == bufferMeans.length) {
+ flushBuffer();
+ }
+ bufferMeans[bufferCount] = value;
+ bufferWeights[bufferCount] = weight;
+ bufferCount++;
+ min = Math.min(min, value);
+ max = Math.max(max, value);
+ }
+
+ /**
+ * Adds every given sample with unit weight.
+ *
+ * @param values the samples to add
+ * @throws IllegalArgumentException if any value is NaN or infinite
+ * @throws NullPointerException if {@code values} is {@code null}
+ */
+ public void addAll(double... values) {
+ for (double value : values) {
+ add(value);
+ }
+ }
+
+ /**
+ * Folds another digest into this one. The result approximates the union of the two streams, which
+ * is what makes t-digests usable as a map-reduce style aggregate.
+ *
+ * @param other the digest to absorb; it is left unchanged apart from its pending buffer being folded in
+ * @throws NullPointerException if {@code other} is {@code null}
+ */
+ public void merge(TDigest other) {
+ other.flushBuffer();
+ for (int i = 0; i < other.centroidCount; i++) {
+ add(other.centroidMeans[i], other.centroidWeights[i]);
+ }
+ if (!other.isEmpty()) {
+ min = Math.min(min, other.min);
+ max = Math.max(max, other.max);
+ }
+ }
+
+ /**
+ * Estimates the value below which the given fraction of the stream lies.
+ *
+ * @param q the requested quantile, between 0 and 1 inclusive
+ * @return the estimated quantile; exactly {@link #min()} for {@code q == 0} and {@link #max()} for {@code q == 1}
+ * @throws IllegalArgumentException if {@code q} is outside {@code [0, 1]} or is NaN
+ * @throws IllegalStateException if no sample has been added yet
+ */
+ public double quantile(double q) {
+ if (!(q >= 0.0) || !(q <= 1.0)) {
+ throw new IllegalArgumentException("The quantile probability must lie in [0, 1], but was " + q);
+ }
+ flushBuffer();
+ requireNonEmpty();
+ if (centroidCount == 1) {
+ return centroidMeans[0];
+ }
+
+ double index = q * totalWeight;
+ if (index <= 0.0) {
+ return min;
+ }
+ if (index >= totalWeight) {
+ return max;
+ }
+
+ // The centroids are treated as knots of a piecewise linear quantile function, each sitting at
+ // the centre of the weight it carries, with min and max closing the two ends.
+ double previousValue = min;
+ double previousIndex = 0.0;
+ double currentIndex = 0.0;
+ for (int i = 0; i < centroidCount; i++) {
+ currentIndex += i == 0 ? centroidWeights[0] / 2.0 : (centroidWeights[i - 1] + centroidWeights[i]) / 2.0;
+ if (index < currentIndex) {
+ return interpolate(previousIndex, previousValue, currentIndex, centroidMeans[i], index);
+ }
+ previousValue = centroidMeans[i];
+ previousIndex = currentIndex;
+ }
+ return interpolate(previousIndex, previousValue, totalWeight, max, index);
+ }
+
+ /**
+ * Estimates the fraction of the stream that is smaller than the given value, i.e. the empirical
+ * cumulative distribution function.
+ *
+ * @param value the value to look up
+ * @return a number in {@code [0, 1]}
+ * @throws IllegalArgumentException if {@code value} is NaN
+ * @throws IllegalStateException if no sample has been added yet
+ */
+ public double cdf(double value) {
+ if (Double.isNaN(value)) {
+ throw new IllegalArgumentException("The value must not be NaN");
+ }
+ flushBuffer();
+ requireNonEmpty();
+ if (value < min) {
+ return 0.0;
+ }
+ if (value > max) {
+ return 1.0;
+ }
+ if (max <= min) {
+ return 0.5;
+ }
+
+ double previousValue = min;
+ double previousIndex = 0.0;
+ double currentIndex = 0.0;
+ for (int i = 0; i < centroidCount; i++) {
+ currentIndex += i == 0 ? centroidWeights[0] / 2.0 : (centroidWeights[i - 1] + centroidWeights[i]) / 2.0;
+ if (value < centroidMeans[i]) {
+ return interpolate(previousValue, previousIndex, centroidMeans[i], currentIndex, value) / totalWeight;
+ }
+ previousValue = centroidMeans[i];
+ previousIndex = currentIndex;
+ }
+ return interpolate(previousValue, previousIndex, max, totalWeight, value) / totalWeight;
+ }
+
+ /**
+ * Returns the smallest sample ever added, tracked exactly.
+ *
+ * @return the minimum
+ * @throws IllegalStateException if no sample has been added yet
+ */
+ public double min() {
+ requireAnySample();
+ return min;
+ }
+
+ /**
+ * Returns the largest sample ever added, tracked exactly.
+ *
+ * @return the maximum
+ * @throws IllegalStateException if no sample has been added yet
+ */
+ public double max() {
+ requireAnySample();
+ return max;
+ }
+
+ /**
+ * Returns the total weight of everything added, which for unweighted input is the number of
+ * samples.
+ *
+ * @return the accumulated weight
+ */
+ public double totalWeight() {
+ double pending = 0.0;
+ for (int i = 0; i < bufferCount; i++) {
+ pending += bufferWeights[i];
+ }
+ return totalWeight + pending;
+ }
+
+ /**
+ * Returns how many centroids the sketch currently holds, after folding in pending insertions.
+ *
+ * @return the number of centroids, bounded by roughly {@code compression / 2}
+ */
+ public int centroidCount() {
+ flushBuffer();
+ return centroidCount;
+ }
+
+ /**
+ * Returns the compression parameter.
+ *
+ * @return the value given at construction time
+ */
+ public double compression() {
+ return compression;
+ }
+
+ /**
+ * Tells whether the digest holds no samples.
+ *
+ * @return {@code true} if nothing has been added
+ */
+ public boolean isEmpty() {
+ return centroidCount == 0 && bufferCount == 0;
+ }
+
+ /**
+ * Forgets every sample.
+ */
+ public void reset() {
+ centroidCount = 0;
+ bufferCount = 0;
+ totalWeight = 0.0;
+ min = Double.POSITIVE_INFINITY;
+ max = Double.NEGATIVE_INFINITY;
+ }
+
+ @Override
+ public String toString() {
+ return "TDigest{compression=" + compression + ", weight=" + totalWeight() + ", centroids=" + (isEmpty() ? 0 : centroidCount()) + '}';
+ }
+
+ /**
+ * Folds every buffered point into the centroid list.
+ *
+ *
Buffer and centroids are concatenated, sorted by mean and then swept once from the smallest
+ * mean upwards. The sweep keeps filling the current output centroid while doing so would not push
+ * it past the weight limit given by the scale function at the quantile the centroid starts at;
+ * otherwise the centroid is closed and a new one is opened.
+ */
+ private void flushBuffer() {
+ if (bufferCount == 0) {
+ return;
+ }
+
+ int size = centroidCount + bufferCount;
+ System.arraycopy(centroidMeans, 0, scratchMeans, 0, centroidCount);
+ System.arraycopy(centroidWeights, 0, scratchWeights, 0, centroidCount);
+ System.arraycopy(bufferMeans, 0, scratchMeans, centroidCount, bufferCount);
+ System.arraycopy(bufferWeights, 0, scratchWeights, centroidCount, bufferCount);
+ bufferCount = 0;
+ sortByMean(scratchMeans, scratchWeights, 0, size - 1);
+
+ double weight = 0.0;
+ for (int i = 0; i < size; i++) {
+ weight += scratchWeights[i];
+ }
+ totalWeight = weight;
+
+ int last = 0;
+ centroidMeans[0] = scratchMeans[0];
+ centroidWeights[0] = scratchWeights[0];
+ double weightOfClosedCentroids = 0.0;
+ double weightLimit = totalWeight * quantileLimit(0.0);
+
+ for (int i = 1; i < size; i++) {
+ double projected = centroidWeights[last] + scratchWeights[i];
+ boolean roomLeft = weightOfClosedCentroids + projected <= weightLimit;
+ if (roomLeft || last == centroidMeans.length - 1) {
+ centroidWeights[last] = projected;
+ centroidMeans[last] += (scratchMeans[i] - centroidMeans[last]) * scratchWeights[i] / projected;
+ } else {
+ weightOfClosedCentroids += centroidWeights[last];
+ weightLimit = totalWeight * quantileLimit(weightOfClosedCentroids / totalWeight);
+ last++;
+ centroidMeans[last] = scratchMeans[i];
+ centroidWeights[last] = scratchWeights[i];
+ }
+ }
+ centroidCount = last + 1;
+ }
+
+ /**
+ * Returns the quantile at which the centroid starting at quantile {@code q} must be closed, that
+ * is {@code kInverse(k(q) + 1)} for the scale function {@code k}.
+ */
+ private double quantileLimit(double q) {
+ // Rounding in the running weight sum could push the ratio a hair outside [0, 1], which would
+ // turn asin into NaN and silently disable the size limit.
+ double bounded = Math.min(1.0, Math.max(0.0, q));
+ double k = compression / TWO_PI * Math.asin(2.0 * bounded - 1.0) + 1.0;
+ double angle = k * TWO_PI / compression;
+ if (angle >= Math.PI / 2.0) {
+ return 1.0;
+ }
+ if (angle <= -Math.PI / 2.0) {
+ return 0.0;
+ }
+ return (Math.sin(angle) + 1.0) / 2.0;
+ }
+
+ private void requireNonEmpty() {
+ if (centroidCount == 0) {
+ throw new IllegalStateException("The digest has not seen any sample yet");
+ }
+ }
+
+ private void requireAnySample() {
+ if (isEmpty()) {
+ throw new IllegalStateException("The digest has not seen any sample yet");
+ }
+ }
+
+ /**
+ * Linear interpolation between two knots, degenerating to the right knot when they coincide.
+ */
+ private static double interpolate(double x0, double y0, double x1, double y1, double x) {
+ if (x1 <= x0) {
+ return y1;
+ }
+ return y0 + (x - x0) / (x1 - x0) * (y1 - y0);
+ }
+
+ /**
+ * Sorts two parallel arrays by the values of the first one, using quicksort with a
+ * median-of-three pivot and an insertion sort for short ranges.
+ */
+ private static void sortByMean(double[] means, double[] weights, int from, int to) {
+ int low = from;
+ int high = to;
+ while (low < high) {
+ if (high - low < INSERTION_SORT_THRESHOLD) {
+ insertionSort(means, weights, low, high);
+ return;
+ }
+ int pivotIndex = partition(means, weights, low, high);
+ // Recurse into the smaller half and loop on the larger one to keep the stack shallow.
+ if (pivotIndex - low < high - pivotIndex) {
+ sortByMean(means, weights, low, pivotIndex - 1);
+ low = pivotIndex + 1;
+ } else {
+ sortByMean(means, weights, pivotIndex + 1, high);
+ high = pivotIndex - 1;
+ }
+ }
+ }
+
+ private static int partition(double[] means, double[] weights, int low, int high) {
+ int middle = low + (high - low) / 2;
+ if (means[middle] < means[low]) {
+ swap(means, weights, low, middle);
+ }
+ if (means[high] < means[low]) {
+ swap(means, weights, low, high);
+ }
+ if (means[high] < means[middle]) {
+ swap(means, weights, middle, high);
+ }
+ swap(means, weights, middle, high - 1);
+ double pivot = means[high - 1];
+
+ int store = low;
+ for (int i = low; i < high - 1; i++) {
+ if (means[i] < pivot) {
+ swap(means, weights, store, i);
+ store++;
+ }
+ }
+ swap(means, weights, store, high - 1);
+ return store;
+ }
+
+ private static void insertionSort(double[] means, double[] weights, int low, int high) {
+ for (int i = low + 1; i <= high; i++) {
+ double mean = means[i];
+ double weight = weights[i];
+ int j = i - 1;
+ while (j >= low && means[j] > mean) {
+ means[j + 1] = means[j];
+ weights[j + 1] = weights[j];
+ j--;
+ }
+ means[j + 1] = mean;
+ weights[j + 1] = weight;
+ }
+ }
+
+ private static void swap(double[] means, double[] weights, int i, int j) {
+ double mean = means[i];
+ means[i] = means[j];
+ means[j] = mean;
+ double weight = weights[i];
+ weights[i] = weights[j];
+ weights[j] = weight;
+ }
+
+ /**
+ * Returns the centroid means, smallest first. Exposed for tests and for inspecting the shape of
+ * the sketch; the returned array is a copy.
+ *
+ * @return a copy of the centroid means
+ */
+ double[] centroidMeansSnapshot() {
+ flushBuffer();
+ return Arrays.copyOf(centroidMeans, centroidCount);
+ }
+
+ /**
+ * Returns the centroid weights, aligned with {@link #centroidMeansSnapshot()}.
+ *
+ * @return a copy of the centroid weights
+ */
+ double[] centroidWeightsSnapshot() {
+ flushBuffer();
+ return Arrays.copyOf(centroidWeights, centroidCount);
+ }
+}
diff --git a/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java
new file mode 100644
index 000000000000..b220c82542d4
--- /dev/null
+++ b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java
@@ -0,0 +1,203 @@
+package com.thealgorithms.streaming;
+
+/**
+ * Watches the timestamps of a stream for samples that arrive out of order or twice.
+ *
+ *
Every windowed algorithm assumes that time moves forward. When it does not, nothing crashes:
+ * the window simply holds samples that never coexisted, a rate is computed over a negative interval,
+ * and a duplicate counts twice in an average. Retries, buffers flushed after a reconnect, several
+ * producers writing into one topic and a clock stepped backwards all produce exactly that, and the
+ * only cheap defence is to check the order explicitly.
+ *
+ *
Each timestamp is compared with the one immediately before it and classified as
+ * {@link Order#INCREASING}, {@link Order#DUPLICATE} or {@link Order#BACKWARDS}. The checker reports,
+ * it does not reorder or drop anything, so {@link #lastTimestamp()} is always the most recent sample
+ * and not the largest one seen.
+ *
+ *
Besides the counters it keeps the worst backwards step, which is what a caller needs in order to
+ * size a reordering buffer: a stream whose worst violation is 20 milliseconds can be repaired by
+ * holding samples for 20 milliseconds, while one that jumps back an hour cannot be repaired at all.
+ *
+ *
Each sample costs O(1) time and the checker keeps O(1) state. This class is not thread-safe.
+ *
+ * @see Monotonic function
+ */
+public final class TimestampOrderChecker {
+
+ private double lastTimestamp;
+ private double worstBackwardsStep;
+ private boolean started;
+ private long count;
+ private long duplicateCount;
+ private long backwardsCount;
+ private Order lastOrder = Order.INCREASING;
+
+ /**
+ * Feeds the timestamp of one sample.
+ *
+ * @param timestamp when the sample arrived
+ * @return how this timestamp relates to the previous one; the first one is always
+ * {@link Order#INCREASING}
+ * @throws IllegalArgumentException if {@code timestamp} is NaN or infinite
+ */
+ public Order accept(double timestamp) {
+ if (!Double.isFinite(timestamp)) {
+ throw new IllegalArgumentException("Timestamps must be finite, but was " + timestamp);
+ }
+
+ Order order = Order.INCREASING;
+ if (started) {
+ if (timestamp == lastTimestamp) {
+ order = Order.DUPLICATE;
+ duplicateCount++;
+ } else if (timestamp < lastTimestamp) {
+ order = Order.BACKWARDS;
+ backwardsCount++;
+ worstBackwardsStep = Math.max(worstBackwardsStep, lastTimestamp - timestamp);
+ }
+ }
+
+ lastTimestamp = timestamp;
+ started = true;
+ count++;
+ lastOrder = order;
+ return order;
+ }
+
+ /**
+ * Runs the checker over a whole series of timestamps.
+ *
+ * @param timestamps the timestamps to inspect
+ * @return a new array of the same length holding the verdict for every timestamp
+ * @throws IllegalArgumentException if a timestamp is NaN or infinite
+ * @throws NullPointerException if {@code timestamps} is {@code null}
+ */
+ public Order[] scan(double[] timestamps) {
+ Order[] verdicts = new Order[timestamps.length];
+ for (int i = 0; i < timestamps.length; i++) {
+ verdicts[i] = accept(timestamps[i]);
+ }
+ return verdicts;
+ }
+
+ /**
+ * Returns the verdict on the most recent timestamp.
+ *
+ * @return the last verdict, {@link Order#INCREASING} before the first timestamp
+ */
+ public Order lastOrder() {
+ return lastOrder;
+ }
+
+ /**
+ * Tells whether every timestamp so far moved forward.
+ *
+ * @return {@code true} if neither a duplicate nor a backwards step has been seen
+ */
+ public boolean isOrdered() {
+ return duplicateCount == 0 && backwardsCount == 0;
+ }
+
+ /**
+ * Returns the timestamp of the most recent sample, which is not necessarily the largest one seen.
+ *
+ * @return the last timestamp
+ * @throws IllegalStateException if no timestamp has been accepted yet
+ */
+ public double lastTimestamp() {
+ if (!started) {
+ throw new IllegalStateException("The checker has not seen any timestamp yet");
+ }
+ return lastTimestamp;
+ }
+
+ /**
+ * Returns the largest distance a timestamp ever jumped backwards, which is how long a reordering
+ * buffer would have to hold a sample to repair this stream.
+ *
+ * @return the worst backwards step, {@code 0} if the stream never went backwards
+ */
+ public double worstBackwardsStep() {
+ return worstBackwardsStep;
+ }
+
+ /**
+ * Returns how many timestamps have been inspected since the last reset.
+ *
+ * @return the sample count
+ */
+ public long count() {
+ return count;
+ }
+
+ /**
+ * Returns how many timestamps repeated the one before them.
+ *
+ * @return the duplicate count
+ */
+ public long duplicateCount() {
+ return duplicateCount;
+ }
+
+ /**
+ * Returns how many timestamps were smaller than the one before them.
+ *
+ * @return the backwards count
+ */
+ public long backwardsCount() {
+ return backwardsCount;
+ }
+
+ /**
+ * Forgets every timestamp seen so far.
+ */
+ public void reset() {
+ lastTimestamp = 0.0;
+ worstBackwardsStep = 0.0;
+ started = false;
+ count = 0;
+ duplicateCount = 0;
+ backwardsCount = 0;
+ lastOrder = Order.INCREASING;
+ }
+
+ @Override
+ public String toString() {
+ return "TimestampOrderChecker{samples=" + count + ", duplicates=" + duplicateCount + ", backwards=" + backwardsCount + ", worstStep=" + worstBackwardsStep + "}";
+ }
+
+ /**
+ * How a timestamp relates to the one before it.
+ */
+ public enum Order {
+
+ /** The timestamp moved forward, which is the only healthy case. */
+ INCREASING,
+
+ /** The timestamp repeats the previous one. */
+ DUPLICATE,
+
+ /** The timestamp is older than the previous one. */
+ BACKWARDS;
+
+ /**
+ * Tells whether this verdict reports a broken timeline.
+ *
+ * @return {@code true} for {@link #DUPLICATE} and {@link #BACKWARDS}
+ */
+ public boolean isViolation() {
+ return this != INCREASING;
+ }
+ }
+}
diff --git a/src/main/java/com/thealgorithms/strings/BoothsAlgorithm.java b/src/main/java/com/thealgorithms/strings/BoothsAlgorithm.java
new file mode 100644
index 000000000000..01c2f67a8569
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/BoothsAlgorithm.java
@@ -0,0 +1,69 @@
+package com.thealgorithms.strings;
+
+/**
+ * Finds the lexicographically smallest cyclic rotation of a string using
+ * Booth's algorithm.
+ *
+ *
The algorithm compares candidate rotations without materializing them,
+ * running in O(n) time and O(1) auxiliary space.
+ *
+ * @see
+ * Lexicographically minimal string rotation
+ */
+public final class BoothsAlgorithm {
+ private BoothsAlgorithm() {
+ }
+
+ /**
+ * Returns the starting index of the lexicographically smallest cyclic
+ * rotation of {@code input}. If several rotations are equal and minimal,
+ * the algorithm returns the smallest starting index among them.
+ *
+ *
For example, the smallest rotation of {@code "baca"} is
+ * {@code "abac"}, which starts at index {@code 3}.
+ *
+ * @param input the string whose minimal cyclic rotation is sought
+ * @return the starting index of the minimal rotation, or {@code 0} for an
+ * empty string
+ * @throws IllegalArgumentException if {@code input} is {@code null}
+ */
+ public static int minimalRotationIndex(String input) {
+ if (input == null) {
+ throw new IllegalArgumentException("Input string must not be null");
+ }
+
+ int length = input.length();
+ if (length == 0) {
+ return 0;
+ }
+
+ int first = 0;
+ int second = 1;
+ int offset = 0;
+
+ while (first < length && second < length && offset < length) {
+ char firstChar = input.charAt((first + offset) % length);
+ char secondChar = input.charAt((second + offset) % length);
+
+ if (firstChar == secondChar) {
+ offset++;
+ continue;
+ }
+
+ if (firstChar > secondChar) {
+ first += offset + 1;
+ if (first <= second) {
+ first = second + 1;
+ }
+ } else {
+ second += offset + 1;
+ if (second <= first) {
+ second = first + 1;
+ }
+ }
+ offset = 0;
+ }
+
+ return Math.min(first, second);
+ }
+}
diff --git a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
index d9187cbf66c4..51dcdd804b25 100644
--- a/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
+++ b/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
@@ -95,7 +95,7 @@ public static Integer getLastComparisons() {
* @return index of first occurrence of the pattern in the text
*/
private static int firstOccurrence(String pattern, String text, boolean caseSensitive) {
- shiftValues = calcShiftValues(pattern); // build the bad symbol table
+ shiftValues = calcShiftValues(pattern, caseSensitive); // build the bad symbol table
comparisons = 0; // reset comparisons
if (pattern.length() == 0) { // return failure, if pattern empty
@@ -113,7 +113,7 @@ private static int firstOccurrence(String pattern, String text, boolean caseSens
char patternChar = pattern.charAt(i);
char textChar = text.charAt((textIndex + i) - (pattern.length() - 1));
if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern
- textIndex += getShiftValue(text.charAt(textIndex));
+ textIndex += getShiftValue(text.charAt(textIndex), caseSensitive);
break;
}
i--;
@@ -153,14 +153,15 @@ private static boolean charEquals(char c1, char c2, boolean caseSensitive) {
* in the table, then it is not a rightmost occurrence, so it continues.
*
* @param pattern basis for the bad symbol table
+ * @param caseSensitive whether to build the table with case-sensitive keys
* @return the bad symbol table
*/
- private static HashMap calcShiftValues(String pattern) {
+ private static HashMap calcShiftValues(String pattern, boolean caseSensitive) {
patternLength = pattern.length();
HashMap table = new HashMap<>();
for (int i = pattern.length() - 2; i >= 0; i--) { // length - 2 is the index of the second to last character
- char c = pattern.charAt(i);
+ char c = caseSensitive ? pattern.charAt(i) : Character.toLowerCase(pattern.charAt(i));
int finalI = i;
table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI);
}
@@ -173,11 +174,14 @@ private static HashMap calcShiftValues(String pattern) {
* appropriate shift value for a given character
*
* @param c character
+ * @param caseSensitive whether the table was built with case-sensitive keys
* @return shift value that corresponds to the character argument
*/
- private static Integer getShiftValue(char c) {
- if (shiftValues.get(c) != null) {
- return shiftValues.get(c);
+ private static Integer getShiftValue(char c, boolean caseSensitive) {
+ // the table holds lower-case keys for case-insensitive searches
+ char key = caseSensitive ? c : Character.toLowerCase(c);
+ if (shiftValues.get(key) != null) {
+ return shiftValues.get(key);
} else {
return patternLength;
}
diff --git a/src/main/java/com/thealgorithms/strings/LyndonFactorization.java b/src/main/java/com/thealgorithms/strings/LyndonFactorization.java
new file mode 100644
index 000000000000..3eb13b00d0fb
--- /dev/null
+++ b/src/main/java/com/thealgorithms/strings/LyndonFactorization.java
@@ -0,0 +1,61 @@
+package com.thealgorithms.strings;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Factorizes a string into its Lyndon words using Duval's algorithm.
+ *
+ *
Duval's algorithm runs in O(n) time and uses O(1) auxiliary working
+ * space, excluding the returned list and its strings.
+ *
+ *
Reference:
+ * https://cp-algorithms.com/string/lyndon_factorization.html
+ */
+public final class LyndonFactorization {
+ private LyndonFactorization() {
+ }
+
+ /**
+ * Returns the standard Lyndon factorization of {@code text}.
+ *
+ *