repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/DarkSort.java
src/main/java/com/thealgorithms/sorts/DarkSort.java
package com.thealgorithms.sorts; /** * Dark Sort algorithm implementation. * * Dark Sort uses a temporary array to count occurrences of elements and * reconstructs the sorted array based on the counts. */ class DarkSort { /** * Sorts the array using the Dark Sort algorithm. * * @param unsorted the array to be sorted * @return sorted array */ public Integer[] sort(Integer[] unsorted) { if (unsorted == null || unsorted.length <= 1) { return unsorted; } int max = findMax(unsorted); // Find the maximum value in the array // Create a temporary array for counting occurrences int[] temp = new int[max + 1]; // Count occurrences of each element for (int value : unsorted) { temp[value]++; } // Reconstruct the sorted array int index = 0; for (int i = 0; i < temp.length; i++) { while (temp[i] > 0) { unsorted[index++] = i; temp[i]--; } } return unsorted; } /** * Helper method to find the maximum value in an array. * * @param arr the array * @return the maximum value */ private int findMax(Integer[] arr) { int max = arr[0]; for (int value : arr) { if (value > max) { max = value; } } return max; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/BubbleSort.java
src/main/java/com/thealgorithms/sorts/BubbleSort.java
package com.thealgorithms.sorts; /** * @author Varun Upadhyay (https://github.com/varunu28) * @author Podshivalov Nikita (https://github.com/nikitap492) * @see SortAlgorithm */ class BubbleSort implements SortAlgorithm { /** * Implements generic bubble sort algorithm. * * Time Complexity: * - Best case: O(n) – array is already sorted. * - Average case: O(n^2) * - Worst case: O(n^2) * * Space Complexity: O(1) – in-place sorting. * * @param array the array to be sorted. * @param <T> the type of elements in the array. * @return the sorted array. */ @Override public <T extends Comparable<T>> T[] sort(T[] array) { for (int i = 1, size = array.length; i < size; ++i) { boolean swapped = false; for (int j = 0; j < size - i; ++j) { if (SortUtils.greater(array[j], array[j + 1])) { SortUtils.swap(array, j, j + 1); swapped = true; } } if (!swapped) { break; } } return array; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java
src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java
package com.thealgorithms.sorts; /** * CocktailShakerSort class implements the Cocktail Shaker Sort algorithm, * which is a bidirectional bubble sort. It sorts the array by passing * through it back and forth, progressively moving the largest elements * to the end and the smallest elements to the beginning. * * @author Mateus Bizzo (https://github.com/MattBizzo) * @author Podshivalov Nikita (https://github.com/nikitap492) */ class CocktailShakerSort implements SortAlgorithm { /** * Sorts the given array using the Cocktail Shaker Sort algorithm. * * @param <T> The type of elements in the array, which must be comparable * @param array The array to be sorted * @return The sorted array */ @Override public <T extends Comparable<T>> T[] sort(final T[] array) { if (array.length == 0) { return array; } int left = 0; int right = array.length - 1; while (left < right) { right = performForwardPass(array, left, right); left = performBackwardPass(array, left, right); } return array; } /** * Performs a forward pass through the array, moving larger elements to the end. * * @param <T> The type of elements in the array, which must be comparable * @param array The array being sorted * @param left The current left boundary of the sorting area * @param right The current right boundary of the sorting area * @return The index of the last swapped element during this pass */ private <T extends Comparable<T>> int performForwardPass(final T[] array, final int left, final int right) { int lastSwappedIndex = left; for (int i = left; i < right; i++) { if (SortUtils.less(array[i + 1], array[i])) { SortUtils.swap(array, i, i + 1); lastSwappedIndex = i; } } return lastSwappedIndex; } /** * Performs a backward pass through the array, moving smaller elements to the beginning. * * @param <T> The type of elements in the array, which must be comparable * @param array The array being sorted * @param left The current left boundary of the sorting area * @param right The current right boundary of the sorting area * @return The index of the last swapped element during this pass */ private <T extends Comparable<T>> int performBackwardPass(final T[] array, final int left, final int right) { int lastSwappedIndex = right; for (int i = right; i > left; i--) { if (SortUtils.less(array[i], array[i - 1])) { SortUtils.swap(array, i - 1, i); lastSwappedIndex = i; } } return lastSwappedIndex; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SelectionSortRecursive.java
src/main/java/com/thealgorithms/sorts/SelectionSortRecursive.java
package com.thealgorithms.sorts; /** * Class that implements the Selection Sort algorithm using recursion. */ public class SelectionSortRecursive implements SortAlgorithm { /** * Sorts an array using recursive selection sort. * * @param array the array to be sorted * @param <T> the type of elements in the array (must be Comparable) * @return the sorted array */ public <T extends Comparable<T>> T[] sort(T[] array) { if (array.length == 0) { return array; } recursiveSelectionSort(array, 0); return array; } /** * Recursively sorts the array using selection sort. * * @param array the array to be sorted * @param index the current index to start sorting from * @param <T> the type of elements in the array (must be Comparable) */ private static <T extends Comparable<T>> void recursiveSelectionSort(T[] array, final int index) { if (index == array.length - 1) { return; } SortUtils.swap(array, index, findMinIndex(array, index)); // Recursively call selection sort for the remaining array recursiveSelectionSort(array, index + 1); } /** * Finds the index of the minimum element in the array starting from the given index. * * @param array the array to search * @param start the starting index for the search * @param <T> the type of elements in the array * @return the index of the minimum element */ private static <T extends Comparable<T>> int findMinIndex(T[] array, final int start) { // Base case: if start is the last index, return start if (start == array.length - 1) { return start; } // Recursive call to find the minimum index in the rest of the array final int minIndexInRest = findMinIndex(array, start + 1); // Return the index of the smaller element between array[start] and the minimum element in the rest of the array return SortUtils.less(array[start], array[minIndexInRest]) ? start : minIndexInRest; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/sorts/SlowSort.java
src/main/java/com/thealgorithms/sorts/SlowSort.java
package com.thealgorithms.sorts; /** * @author Amir Hassan (https://github.com/ahsNT) * @see SortAlgorithm */ public class SlowSort implements SortAlgorithm { @Override public <T extends Comparable<T>> T[] sort(T[] unsortedArray) { sort(unsortedArray, 0, unsortedArray.length - 1); return unsortedArray; } private <T extends Comparable<T>> void sort(T[] array, int i, int j) { if (SortUtils.greaterOrEqual(i, j)) { return; } final int m = (i + j) >>> 1; sort(array, i, m); sort(array, m + 1, j); if (SortUtils.less(array[j], array[m])) { SortUtils.swap(array, j, m); } sort(array, i, j - 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java
src/main/java/com/thealgorithms/lineclipping/LiangBarsky.java
package com.thealgorithms.lineclipping; import com.thealgorithms.lineclipping.utils.Line; import com.thealgorithms.lineclipping.utils.Point; /** * @author shikarisohan * @since 10/5/24 * * * The Liang-Barsky line clipping algorithm is an efficient algorithm for * * line clipping against a rectangular window. It is based on the parametric * * equation of a line and checks the intersections of the line with the * * window boundaries. This algorithm calculates the intersection points, * * if any, and returns the clipped line that lies inside the window. * * * * Reference: * * https://en.wikipedia.org/wiki/Liang%E2%80%93Barsky_algorithm * * Clipping window boundaries are defined as (xMin, yMin) and (xMax, yMax). * The algorithm computes the clipped line segment if it's partially or * fully inside the clipping window. */ public class LiangBarsky { // Define the clipping window double xMin; double xMax; double yMin; double yMax; public LiangBarsky(double xMin, double yMin, double xMax, double yMax) { this.xMin = xMin; this.yMin = yMin; this.xMax = xMax; this.yMax = yMax; } // Liang-Barsky algorithm to return the clipped line public Line liangBarskyClip(Line line) { double dx = line.end.x - line.start.x; double dy = line.end.y - line.start.y; double[] p = {-dx, dx, -dy, dy}; double[] q = {line.start.x - xMin, xMax - line.start.x, line.start.y - yMin, yMax - line.start.y}; double[] resultT = clipLine(p, q); if (resultT == null) { return null; // Line is outside the clipping window } return calculateClippedLine(line, resultT[0], resultT[1], dx, dy); } // clip the line by adjusting t0 and t1 for each edge private double[] clipLine(double[] p, double[] q) { double t0 = 0.0; double t1 = 1.0; for (int i = 0; i < 4; i++) { double t = q[i] / p[i]; if (p[i] == 0 && q[i] < 0) { return null; // Line is outside the boundary } else if (p[i] < 0) { if (t > t1) { return null; } // Line is outside if (t > t0) { t0 = t; } // Update t0 } else if (p[i] > 0) { if (t < t0) { return null; } // Line is outside if (t < t1) { t1 = t; } // Update t1 } } return new double[] {t0, t1}; // Return valid t0 and t1 } // calculate the clipped line based on t0 and t1 private Line calculateClippedLine(Line line, double t0, double t1, double dx, double dy) { double clippedX1 = line.start.x + t0 * dx; double clippedY1 = line.start.y + t0 * dy; double clippedX2 = line.start.x + t1 * dx; double clippedY2 = line.start.y + t1 * dy; return new Line(new Point(clippedX1, clippedY1), new Point(clippedX2, clippedY2)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java
src/main/java/com/thealgorithms/lineclipping/CohenSutherland.java
package com.thealgorithms.lineclipping; import com.thealgorithms.lineclipping.utils.Line; import com.thealgorithms.lineclipping.utils.Point; /** * @author shikarisohan * @since 10/4/24 * Cohen-Sutherland Line Clipping Algorithm * * This algorithm is used to clip a line segment to a rectangular window. * It assigns a region code to each endpoint of the line segment, and * then efficiently determines whether the line segment is fully inside, * fully outside, or partially inside the window. * * Reference: * https://en.wikipedia.org/wiki/Cohen%E2%80%93Sutherland_algorithm * * Clipping window boundaries are defined as (xMin, yMin) and (xMax, yMax). * The algorithm computes the clipped line segment if it's partially or * fully inside the clipping window. */ public class CohenSutherland { // Region codes for the 9 regions private static final int INSIDE = 0; // 0000 private static final int LEFT = 1; // 0001 private static final int RIGHT = 2; // 0010 private static final int BOTTOM = 4; // 0100 private static final int TOP = 8; // 1000 // Define the clipping window double xMin; double yMin; double xMax; double yMax; public CohenSutherland(double xMin, double yMin, double xMax, double yMax) { this.xMin = xMin; this.yMin = yMin; this.xMax = xMax; this.yMax = yMax; } // Compute the region code for a point (x, y) private int computeCode(double x, double y) { int code = INSIDE; if (x < xMin) // to the left of rectangle { code |= LEFT; } else if (x > xMax) // to the right of rectangle { code |= RIGHT; } if (y < yMin) // below the rectangle { code |= BOTTOM; } else if (y > yMax) // above the rectangle { code |= TOP; } return code; } // Cohen-Sutherland algorithm to return the clipped line public Line cohenSutherlandClip(Line line) { double x1 = line.start.x; double y1 = line.start.y; double x2 = line.end.x; double y2 = line.end.y; int code1 = computeCode(x1, y1); int code2 = computeCode(x2, y2); boolean accept = false; while (true) { if ((code1 == 0) && (code2 == 0)) { // Both points are inside the rectangle accept = true; break; } else if ((code1 & code2) != 0) { // Both points are outside the rectangle in the same region break; } else { // Some segment of the line is inside the rectangle double x = 0; double y = 0; // Pick an endpoint that is outside the rectangle int codeOut = (code1 != 0) ? code1 : code2; // Find the intersection point using the line equation if ((codeOut & TOP) != 0) { // Point is above the rectangle x = x1 + (x2 - x1) * (yMax - y1) / (y2 - y1); y = yMax; } else if ((codeOut & BOTTOM) != 0) { // Point is below the rectangle x = x1 + (x2 - x1) * (yMin - y1) / (y2 - y1); y = yMin; } else if ((codeOut & RIGHT) != 0) { // Point is to the right of the rectangle y = y1 + (y2 - y1) * (xMax - x1) / (x2 - x1); x = xMax; } else if ((codeOut & LEFT) != 0) { // Point is to the left of the rectangle y = y1 + (y2 - y1) * (xMin - x1) / (x2 - x1); x = xMin; } // Replace the point outside the rectangle with the intersection point if (codeOut == code1) { x1 = x; y1 = y; code1 = computeCode(x1, y1); } else { x2 = x; y2 = y; code2 = computeCode(x2, y2); } } } if (accept) { return new Line(new Point(x1, y1), new Point(x2, y2)); } else { return null; // The line is fully rejected } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/lineclipping/utils/Line.java
src/main/java/com/thealgorithms/lineclipping/utils/Line.java
package com.thealgorithms.lineclipping.utils; import java.util.Objects; /** * @author moksedursohan * @since 10/4/24 */ public class Line { public Point start; public Point end; public Line() { } public Line(Point start, Point end) { this.start = start; this.end = end; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Line line)) { return false; } return Objects.equals(start, line.start) && Objects.equals(end, line.end); } @Override public int hashCode() { return Objects.hash(start, end); } @Override public String toString() { return "Line from " + start + " to " + end; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/lineclipping/utils/Point.java
src/main/java/com/thealgorithms/lineclipping/utils/Point.java
package com.thealgorithms.lineclipping.utils; import java.util.Objects; /** * @author moksedursohan * @since 10/4/24 */ public class Point { public double x; public double y; public Point() { } public Point(double x, double y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Point point)) { return false; } return Double.compare(x, point.x) == 0 && Double.compare(y, point.y) == 0; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public String toString() { return "(" + x + ", " + y + ")"; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/nodes/Node.java
src/main/java/com/thealgorithms/devutils/nodes/Node.java
package com.thealgorithms.devutils.nodes; /** * Base class for any node implementation which contains a generic type * variable. * * All known subclasses: {@link TreeNode}, {@link SimpleNode}. * * @param <E> The type of the data held in the Node. * * @author <a href="https://github.com/aitorfi">aitorfi</a> */ public abstract class Node<E> { /** * Generic type data stored in the Node. */ private E data; /** * Empty constructor. */ public Node() { } /** * Initializes the Nodes' data. * * @param data Value to which data will be initialized. */ public Node(E data) { this.data = data; } public E getData() { return data; } public void setData(E data) { this.data = data; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java
src/main/java/com/thealgorithms/devutils/nodes/SimpleNode.java
package com.thealgorithms.devutils.nodes; /** * Simple Node implementation that holds a reference to the next Node. * * @param <E> The type of the data held in the Node. * * @author <a href="https://github.com/aitorfi">aitorfi</a> */ public class SimpleNode<E> extends Node<E> { /** * Reference to the next Node. */ private SimpleNode<E> nextNode; /** * Empty constructor. */ public SimpleNode() { super(); } /** * Initializes the Nodes' data. * * @param data Value to which data will be initialized. * @see Node#Node(Object) */ public SimpleNode(E data) { super(data); } /** * Initializes the Nodes' data and next node reference. * * @param data Value to which data will be initialized. * @param nextNode Value to which the next node reference will be set. */ public SimpleNode(E data, SimpleNode<E> nextNode) { super(data); this.nextNode = nextNode; } /** * @return True if there is a next node, otherwise false. */ public boolean hasNext() { return (nextNode != null); } public SimpleNode<E> getNextNode() { return nextNode; } public void setNextNode(SimpleNode<E> nextNode) { this.nextNode = nextNode; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java
src/main/java/com/thealgorithms/devutils/nodes/TreeNode.java
package com.thealgorithms.devutils.nodes; /** * Base class for any tree node which holds a reference to the parent node. * * All known subclasses: {@link SimpleTreeNode}, {@link LargeTreeNode}. * * @param <E> The type of the data held in the Node. * * @author <a href="https://github.com/aitorfi">aitorfi</a> */ public abstract class TreeNode<E> extends Node<E> { /** * Reference to the parent Node. */ private TreeNode<E> parentNode; /** * Indicates the depth at which this node is in the tree. */ private int depth; /** * Empty constructor. */ public TreeNode() { super(); depth = 0; } /** * Initializes the Nodes' data. * * @param data Value to which data will be initialized. * @see Node#Node(Object) */ public TreeNode(E data) { super(data); depth = 0; } /** * Initializes the Nodes' data and parent node reference. * * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. */ public TreeNode(E data, TreeNode<E> parentNode) { super(data); this.parentNode = parentNode; depth = this.parentNode.getDepth() + 1; } /** * @return True if the node is a leaf node, otherwise false. */ public abstract boolean isLeafNode(); /** * @return True if the node is the root node, otherwise false. */ public boolean isRootNode() { return (parentNode == null); } public TreeNode<E> getParent() { return parentNode; } public void setParent(TreeNode<E> parentNode) { this.parentNode = parentNode; depth = this.parentNode.getDepth() + 1; } public int getDepth() { return depth; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
package com.thealgorithms.devutils.nodes; import java.util.Collection; /** * {@link TreeNode} extension that holds a {@link Collection} of references to * child Nodes. * * @param <E> The type of the data held in the Node. * * @author <a href="https://github.com/aitorfi">aitorfi</a> */ public class LargeTreeNode<E> extends TreeNode<E> { /** * {@link Collection} that holds the Nodes' child nodes. */ private Collection<LargeTreeNode<E>> childNodes; /** * Empty constructor. */ public LargeTreeNode() { super(); } /** * Initializes the Nodes' data. * * @param data Value to which data will be initialized. * @see TreeNode#TreeNode(Object) */ public LargeTreeNode(E data) { super(data); } /** * Initializes the Nodes' data and parent node reference. * * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @see TreeNode#TreeNode(Object, Node) */ public LargeTreeNode(E data, LargeTreeNode<E> parentNode) { super(data, parentNode); } /** * Initializes the Nodes' data and parent and child nodes references. * * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @param childNodes {@link Collection} of child Nodes. * @see TreeNode#TreeNode(Object, Node) */ public LargeTreeNode(E data, LargeTreeNode<E> parentNode, Collection<LargeTreeNode<E>> childNodes) { super(data, parentNode); this.childNodes = childNodes; } /** * @return True if the node is a leaf node, otherwise false. * @see TreeNode#isLeafNode() */ @Override public boolean isLeafNode() { return (childNodes == null || childNodes.isEmpty()); } public Collection<LargeTreeNode<E>> getChildNodes() { return childNodes; } public void setChildNodes(Collection<LargeTreeNode<E>> childNodes) { this.childNodes = childNodes; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java
src/main/java/com/thealgorithms/devutils/nodes/SimpleTreeNode.java
package com.thealgorithms.devutils.nodes; /** * Simple TreeNode extension that holds references to two child Nodes (left and * right). * * @param <E> The type of the data held in the Node. * * @author <a href="https://github.com/aitorfi">aitorfi</a> */ public class SimpleTreeNode<E> extends TreeNode<E> { /** * Reference to the child Node on the left. */ private SimpleTreeNode<E> leftNode; /** * Reference to the child Node on the right. */ private SimpleTreeNode<E> rightNode; /** * Empty constructor. */ public SimpleTreeNode() { super(); } /** * Initializes the Nodes' data. * * @param data Value to which data will be initialized. * @see TreeNode#TreeNode(Object) */ public SimpleTreeNode(E data) { super(data); } /** * Initializes the Nodes' data and parent node reference. * * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @see TreeNode#TreeNode(Object, Node) */ public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode) { super(data, parentNode); } /** * Initializes the Nodes' data and parent and child nodes references. * * @param data Value to which data will be initialized. * @param parentNode Value to which the nodes' parent reference will be set. * @param leftNode Value to which the nodes' left child reference will be * set. * @param rightNode Value to which the nodes' right child reference will be * set. */ public SimpleTreeNode(E data, SimpleTreeNode<E> parentNode, SimpleTreeNode<E> leftNode, SimpleTreeNode<E> rightNode) { super(data, parentNode); this.leftNode = leftNode; this.rightNode = rightNode; } /** * @return True if the node is a leaf node, otherwise false. * @see TreeNode#isLeafNode() */ @Override public boolean isLeafNode() { return (leftNode == null && rightNode == null); } public SimpleTreeNode<E> getLeftNode() { return leftNode; } public void setLeftNode(SimpleTreeNode<E> leftNode) { this.leftNode = leftNode; } public SimpleTreeNode<E> getRightNode() { return rightNode; } public void setRightNode(SimpleTreeNode<E> rightNode) { this.rightNode = rightNode; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java
src/main/java/com/thealgorithms/devutils/entities/ProcessDetails.java
package com.thealgorithms.devutils.entities; public class ProcessDetails { private String processId; private int arrivalTime; private int burstTime; private int waitingTime; private int turnAroundTime; private int priority; public ProcessDetails(final String processId, final int arrivalTime, final int burstTime, int priority) { this.processId = processId; this.arrivalTime = arrivalTime; this.burstTime = burstTime; this.priority = priority; } public ProcessDetails(final String processId, final int arrivalTime, final int burstTime) { this.processId = processId; this.arrivalTime = arrivalTime; this.burstTime = burstTime; } public String getProcessId() { return processId; } public int getArrivalTime() { return arrivalTime; } public int getBurstTime() { return burstTime; } public int getWaitingTime() { return waitingTime; } public int getTurnAroundTimeTime() { return turnAroundTime; } public int getPriority() { return priority; } public void setProcessId(final String processId) { this.processId = processId; } public void setArrivalTime(final int arrivalTime) { this.arrivalTime = arrivalTime; } public void setBurstTime(final int burstTime) { this.burstTime = burstTime; } public void setWaitingTime(final int waitingTime) { this.waitingTime = waitingTime; } public void setTurnAroundTimeTime(final int turnAroundTime) { this.turnAroundTime = turnAroundTime; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java
src/main/java/com/thealgorithms/devutils/searches/SearchAlgorithm.java
package com.thealgorithms.devutils.searches; /** * The common interface of most searching algorithms * * @author Podshivalov Nikita (https://github.com/nikitap492) */ public interface SearchAlgorithm { /** * @param key is an element which should be found * @param array is an array where the element should be found * @param <T> Comparable type * @return first found index of the element */ <T extends Comparable<T>> int find(T[] array, T key); }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java
src/main/java/com/thealgorithms/devutils/searches/MatrixSearchAlgorithm.java
package com.thealgorithms.devutils.searches; /** * The common interface of most searching algorithms that search in matrixes. * * @author Aitor Fidalgo (https://github.com/aitorfi) */ public interface MatrixSearchAlgorithm { /** * @param key is an element which should be found * @param matrix is a matrix where the element should be found * @param <T> Comparable type * @return array containing the first found coordinates of the element */ <T extends Comparable<T>> int[] find(T[][] matrix, T key); }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/puzzlesandgames/TowerOfHanoi.java
src/main/java/com/thealgorithms/puzzlesandgames/TowerOfHanoi.java
package com.thealgorithms.puzzlesandgames; import java.util.List; /** * The {@code TowerOfHanoi} class provides a recursive solution to the Tower of Hanoi puzzle. * This puzzle involves moving a set of discs from one pole to another, following specific rules: * 1. Only one disc can be moved at a time. * 2. A disc can only be placed on top of a larger disc. * 3. All discs must start on one pole and end on another. * * This implementation recursively calculates the steps required to solve the puzzle and stores them * in a provided list. * * <p> * For more information about the Tower of Hanoi, see * <a href="https://en.wikipedia.org/wiki/Tower_of_Hanoi">Tower of Hanoi on Wikipedia</a>. * </p> * * The {@code shift} method takes the number of discs and the names of the poles, * and appends the steps required to solve the puzzle to the provided list. * Time Complexity: O(2^n) - Exponential time complexity due to the recursive nature of the problem. * Space Complexity: O(n) - Linear space complexity due to the recursion stack. * Wikipedia: https://en.wikipedia.org/wiki/Tower_of_Hanoi */ final class TowerOfHanoi { private TowerOfHanoi() { } /** * Recursively solve the Tower of Hanoi puzzle by moving discs between poles. * * @param n The number of discs to move. * @param startPole The name of the start pole from which discs are moved. * @param intermediatePole The name of the intermediate pole used as a temporary holding area. * @param endPole The name of the end pole to which discs are moved. * @param result A list to store the steps required to solve the puzzle. * * <p> * This method is called recursively to move n-1 discs * to the intermediate pole, * then moves the nth disc to the end pole, and finally * moves the n-1 discs from the * intermediate pole to the end pole. * </p> * * <p> * Time Complexity: O(2^n) - Exponential time complexity due to the recursive nature of the problem. * Space Complexity: O(n) - Linear space complexity due to the recursion stack. * </p> */ public static void shift(int n, String startPole, String intermediatePole, String endPole, List<String> result) { if (n != 0) { // Move n-1 discs from startPole to intermediatePole shift(n - 1, startPole, endPole, intermediatePole, result); // Add the move of the nth disc from startPole to endPole result.add(String.format("Move %d from %s to %s", n, startPole, endPole)); // Move the n-1 discs from intermediatePole to endPole shift(n - 1, intermediatePole, startPole, endPole, result); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java
src/main/java/com/thealgorithms/puzzlesandgames/WordBoggle.java
package com.thealgorithms.puzzlesandgames; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public final class WordBoggle { private WordBoggle() { } /** * O(nm * 8^s + ws) time where n = width of boggle board, m = height of * boggle board, s = length of longest word in string array, w = length of * string array, 8 is due to 8 explorable neighbours O(nm + ws) space. */ public static List<String> boggleBoard(char[][] board, String[] words) { Trie trie = new Trie(); for (String word : words) { trie.add(word); } Set<String> finalWords = new HashSet<>(); boolean[][] visited = new boolean[board.length][board.length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[i].length; j++) { explore(i, j, board, trie.root, visited, finalWords); } } return new ArrayList<>(finalWords); } public static void explore(int i, int j, char[][] board, TrieNode trieNode, boolean[][] visited, Set<String> finalWords) { if (visited[i][j]) { return; } char letter = board[i][j]; if (!trieNode.children.containsKey(letter)) { return; } visited[i][j] = true; trieNode = trieNode.children.get(letter); if (trieNode.children.containsKey('*')) { finalWords.add(trieNode.word); } List<Integer[]> neighbors = getNeighbors(i, j, board); for (Integer[] neighbor : neighbors) { explore(neighbor[0], neighbor[1], board, trieNode, visited, finalWords); } visited[i][j] = false; } public static List<Integer[]> getNeighbors(int i, int j, char[][] board) { List<Integer[]> neighbors = new ArrayList<>(); if (i > 0 && j > 0) { neighbors.add(new Integer[] {i - 1, j - 1}); } if (i > 0 && j < board[0].length - 1) { neighbors.add(new Integer[] {i - 1, j + 1}); } if (i < board.length - 1 && j < board[0].length - 1) { neighbors.add(new Integer[] {i + 1, j + 1}); } if (i < board.length - 1 && j > 0) { neighbors.add(new Integer[] {i + 1, j - 1}); } if (i > 0) { neighbors.add(new Integer[] {i - 1, j}); } if (i < board.length - 1) { neighbors.add(new Integer[] {i + 1, j}); } if (j > 0) { neighbors.add(new Integer[] {i, j - 1}); } if (j < board[0].length - 1) { neighbors.add(new Integer[] {i, j + 1}); } return neighbors; } } // Trie used to optimize string search class TrieNode { Map<Character, TrieNode> children = new HashMap<>(); String word = ""; } class Trie { TrieNode root; char endSymbol; Trie() { this.root = new TrieNode(); this.endSymbol = '*'; } public void add(String str) { TrieNode node = this.root; for (int i = 0; i < str.length(); i++) { char letter = str.charAt(i); if (!node.children.containsKey(letter)) { TrieNode newNode = new TrieNode(); node.children.put(letter, newNode); } node = node.children.get(letter); } node.children.put(this.endSymbol, null); node.word = str; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubsequence.java
package com.thealgorithms.dynamicprogramming; /** * Algorithm explanation * https://www.educative.io/edpresso/longest-palindromic-subsequence-algorithm */ public final class LongestPalindromicSubsequence { private LongestPalindromicSubsequence() { } public static void main(String[] args) { String a = "BBABCBCAB"; String b = "BABCBAB"; String aLPS = lps(a); String bLPS = lps(b); System.out.println(a + " => " + aLPS); System.out.println(b + " => " + bLPS); } public static String lps(String original) throws IllegalArgumentException { StringBuilder reverse = new StringBuilder(original); reverse = reverse.reverse(); return recursiveLPS(original, reverse.toString()); } private static String recursiveLPS(String original, String reverse) { String bestResult = ""; // no more chars, then return empty if (original.length() == 0 || reverse.length() == 0) { bestResult = ""; } else { // if the last chars match, then remove it from both strings and recur if (original.charAt(original.length() - 1) == reverse.charAt(reverse.length() - 1)) { String bestSubResult = recursiveLPS(original.substring(0, original.length() - 1), reverse.substring(0, reverse.length() - 1)); bestResult = reverse.charAt(reverse.length() - 1) + bestSubResult; } else { // otherwise (1) ignore the last character of reverse, and recur on original and // updated reverse again (2) ignore the last character of original and recur on the // updated original and reverse again then select the best result from these two // subproblems. String bestSubResult1 = recursiveLPS(original, reverse.substring(0, reverse.length() - 1)); String bestSubResult2 = recursiveLPS(original.substring(0, original.length() - 1), reverse); if (bestSubResult1.length() > bestSubResult2.length()) { bestResult = bestSubResult1; } else { bestResult = bestSubResult2; } } } return bestResult; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
package com.thealgorithms.dynamicprogramming; /** * Given a string containing just the characters '(' and ')', find the length of * the longest valid (well-formed) parentheses substring. * * @author Libin Yang (https://github.com/yanglbme) * @since 2018/10/5 */ public final class LongestValidParentheses { private LongestValidParentheses() { } public static int getLongestValidParentheses(String s) { if (s == null || s.length() < 2) { return 0; } char[] chars = s.toCharArray(); int n = chars.length; int[] res = new int[n]; res[0] = 0; res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; int max = res[1]; for (int i = 2; i < n; ++i) { if (chars[i] == ')') { if (chars[i - 1] == '(') { res[i] = res[i - 2] + 2; } else { int index = i - res[i - 1] - 1; if (index >= 0 && chars[index] == '(') { // ()(()) res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); } } } max = Math.max(max, res[i]); } return max; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
package com.thealgorithms.dynamicprogramming; /** * The {@code Tribonacci} class provides a method to compute the n-th number in the Tribonacci sequence. * N-th Tribonacci Number - https://leetcode.com/problems/n-th-tribonacci-number/description/ */ public final class Tribonacci { private Tribonacci() { } /** * Computes the n-th Tribonacci number. * * @param n the index of the Tribonacci number to compute * @return the n-th Tribonacci number */ public static int compute(int n) { if (n == 0) { return 0; } if (n == 1 || n == 2) { return 1; } int first = 0; int second = 1; int third = 1; for (int i = 3; i <= n; i++) { int next = first + second + third; first = second; second = third; third = next; } return third; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
package com.thealgorithms.dynamicprogramming; import java.util.stream.IntStream; /** * Provides functions to calculate the Levenshtein distance between two strings. * * The Levenshtein distance is a measure of the similarity between two strings by calculating the minimum number of single-character * edits (insertions, deletions, or substitutions) required to change one string into the other. */ public final class LevenshteinDistance { private LevenshteinDistance() { } /** * Calculates the Levenshtein distance between two strings using a naive dynamic programming approach. * * This function computes the Levenshtein distance by constructing a dynamic programming matrix and iteratively filling it in. * It follows the standard top-to-bottom, left-to-right approach for filling in the matrix. * * @param string1 The first string. * @param string2 The second string. * @return The Levenshtein distance between the two input strings. * * Time complexity: O(nm), * Space complexity: O(nm), * * where n and m are lengths of `string1` and `string2`. * * Note that this implementation uses a straightforward dynamic programming approach without any space optimization. * It may consume more memory for larger input strings compared to the optimized version. */ public static int naiveLevenshteinDistance(final String string1, final String string2) { int[][] distanceMatrix = IntStream.rangeClosed(0, string1.length()).mapToObj(i -> IntStream.rangeClosed(0, string2.length()).map(j -> (i == 0) ? j : (j == 0) ? i : 0).toArray()).toArray(int[][] ::new); IntStream.range(1, string1.length() + 1).forEach(i -> IntStream.range(1, string2.length() + 1).forEach(j -> { final int cost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? 0 : 1; distanceMatrix[i][j] = Math.min(distanceMatrix[i - 1][j - 1] + cost, Math.min(distanceMatrix[i][j - 1] + 1, distanceMatrix[i - 1][j] + 1)); })); return distanceMatrix[string1.length()][string2.length()]; } /** * Calculates the Levenshtein distance between two strings using an optimized dynamic programming approach. * * This edit distance is defined as 1 point per insertion, substitution, or deletion required to make the strings equal. * * @param string1 The first string. * @param string2 The second string. * @return The Levenshtein distance between the two input strings. * * Time complexity: O(nm), * Space complexity: O(n), * * where n and m are lengths of `string1` and `string2`. * * Note that this implementation utilizes an optimized dynamic programming approach, significantly reducing the space complexity from O(nm) to O(n), where n and m are the lengths of `string1` and `string2`. * * Additionally, it minimizes space usage by leveraging the shortest string horizontally and the longest string vertically in the computation matrix. */ public static int optimizedLevenshteinDistance(final String string1, final String string2) { if (string1.isEmpty()) { return string2.length(); } int[] previousDistance = IntStream.rangeClosed(0, string1.length()).toArray(); for (int j = 1; j <= string2.length(); j++) { int prevSubstitutionCost = previousDistance[0]; previousDistance[0] = j; for (int i = 1; i <= string1.length(); i++) { final int deletionCost = previousDistance[i] + 1; final int insertionCost = previousDistance[i - 1] + 1; final int substitutionCost = (string1.charAt(i - 1) == string2.charAt(j - 1)) ? prevSubstitutionCost : prevSubstitutionCost + 1; prevSubstitutionCost = previousDistance[i]; previousDistance[i] = Math.min(deletionCost, Math.min(insertionCost, substitutionCost)); } } return previousDistance[string1.length()]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java
src/main/java/com/thealgorithms/dynamicprogramming/PalindromicPartitioning.java
package com.thealgorithms.dynamicprogramming; /** * Provides functionality to solve the Palindrome Partitioning II problem, which involves finding * the minimum number of partitions needed to divide a given string into palindromic substrings. * * <p> * The problem is solved using dynamic programming. The approach involves checking all possible * substrings and determining whether they are palindromes. The minimum number of cuts required * for palindrome partitioning is computed in a bottom-up manner. * </p> * * <p> * Example: * <ul> * <li>Input: "nitik" => Output: 2 (Partitioning: "n | iti | k")</li> * <li>Input: "ababbbabbababa" => Output: 3 (Partitioning: "aba | b | bbabb | ababa")</li> * </ul> * </p> * * @see <a href="https://leetcode.com/problems/palindrome-partitioning-ii/">Palindrome Partitioning II</a> * @see <a href="https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/">Palindrome Partitioning (GeeksforGeeks)</a> */ public final class PalindromicPartitioning { private PalindromicPartitioning() { } public static int minimalPartitions(String word) { int len = word.length(); /* We Make two arrays to create a bottom-up solution. minCuts[i] = Minimum number of cuts needed for palindrome partitioning of substring word[0..i] isPalindrome[i][j] = true if substring str[i..j] is palindrome Base Condition: C[i] is 0 if P[0][i]= true */ int[] minCuts = new int[len]; boolean[][] isPalindrome = new boolean[len][len]; int i; int j; int subLen; // different looping variables // Every substring of length 1 is a palindrome for (i = 0; i < len; i++) { isPalindrome[i][i] = true; } /* subLen is substring length. Build the solution in bottom up manner by considering all * substrings of length starting from 2 to n. */ for (subLen = 2; subLen <= len; subLen++) { // For substring of length subLen, set different possible starting indexes for (i = 0; i < len - subLen + 1; i++) { j = i + subLen - 1; // Ending index // If subLen is 2, then we just need to // compare two characters. Else need to // check two corner characters and value // of P[i+1][j-1] if (subLen == 2) { isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)); } else { isPalindrome[i][j] = (word.charAt(i) == word.charAt(j)) && isPalindrome[i + 1][j - 1]; } } } // We find the minimum for each index for (i = 0; i < len; i++) { if (isPalindrome[0][i]) { minCuts[i] = 0; } else { minCuts[i] = Integer.MAX_VALUE; for (j = 0; j < i; j++) { if (isPalindrome[j + 1][i] && 1 + minCuts[j] < minCuts[i]) { minCuts[i] = 1 + minCuts[j]; } } } } // Return the min cut value for complete // string. i.e., str[0..n-1] return minCuts[len - 1]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
package com.thealgorithms.dynamicprogramming; /** * @author Afrizal Fikri (https://github.com/icalF) */ public final class LongestIncreasingSubsequence { private LongestIncreasingSubsequence() { } private static int upperBound(int[] ar, int l, int r, int key) { while (l < r - 1) { int m = (l + r) >>> 1; if (ar[m] >= key) { r = m; } else { l = m; } } return r; } public static int lis(int[] array) { int len = array.length; if (len == 0) { return 0; } int[] tail = new int[len]; // always points empty slot in tail int length = 1; tail[0] = array[0]; for (int i = 1; i < len; i++) { // new smallest value if (array[i] < tail[0]) { tail[0] = array[i]; } // array[i] extends largest subsequence else if (array[i] > tail[length - 1]) { tail[length++] = array[i]; } // array[i] will become end candidate of an existing subsequence or // Throw away larger elements in all LIS, to make room for upcoming grater elements than // array[i] // (and also, array[i] would have already appeared in one of LIS, identify the location // and replace it) else { tail[upperBound(tail, -1, length - 1, array[i])] = array[i]; } } return length; } /** * @author Alon Firestein (https://github.com/alonfirestein) */ // A function for finding the length of the LIS algorithm in O(nlogn) complexity. public static int findLISLen(int[] a) { final int size = a.length; if (size == 0) { return 0; } int[] arr = new int[size]; arr[0] = a[0]; int lis = 1; for (int i = 1; i < size; i++) { int index = binarySearchBetween(arr, lis - 1, a[i]); arr[index] = a[i]; if (index == lis) { lis++; } } return lis; } // O(logn) private static int binarySearchBetween(int[] t, int end, int key) { int left = 0; int right = end; if (key < t[0]) { return 0; } if (key > t[end]) { return end + 1; } while (left < right - 1) { final int middle = (left + right) >>> 1; if (t[middle] < key) { left = middle; } else { right = middle; } } return right; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
src/main/java/com/thealgorithms/dynamicprogramming/EditDistance.java
package com.thealgorithms.dynamicprogramming; /** * A DynamicProgramming based solution for Edit Distance problem In Java * Description of Edit Distance with an Example: * * <p> * Edit distance is a way of quantifying how dissimilar two strings (e.g., * words) are to one another, by counting the minimum number of operations * required to transform one string into the other. The distance operations are * the removal, insertion, or substitution of a character in the string. * * <p> * * <p> * The Distance between "kitten" and "sitting" is 3. A minimal edit script that * transforms the former into the latter is: * * <p> * kitten → sitten (substitution of "s" for "k") sitten → sittin (substitution * of "i" for "e") sittin → sitting (insertion of "g" at the end). * * @author SUBHAM SANGHAI */ public final class EditDistance { private EditDistance() { } public static int minDistance(String word1, String word2) { int len1 = word1.length(); int len2 = word2.length(); // len1+1, len2+1, because finally return dp[len1][len2] int[][] dp = new int[len1 + 1][len2 + 1]; /* If second string is empty, the only option is to insert all characters of first string into second*/ for (int i = 0; i <= len1; i++) { dp[i][0] = i; } /* If first string is empty, the only option is to insert all characters of second string into first*/ for (int j = 0; j <= len2; j++) { dp[0][j] = j; } // iterate though, and check last char for (int i = 0; i < len1; i++) { char c1 = word1.charAt(i); for (int j = 0; j < len2; j++) { char c2 = word2.charAt(j); // if last two chars equal if (c1 == c2) { // update dp value for +1 length dp[i + 1][j + 1] = dp[i][j]; } else { /* if two characters are different , then take the minimum of the various operations(i.e insertion,removal,substitution)*/ int replace = dp[i][j] + 1; int insert = dp[i][j + 1] + 1; int delete = dp[i + 1][j] + 1; int min = Math.min(replace, insert); min = Math.min(delete, min); dp[i + 1][j + 1] = min; } } } /* return the final answer , after traversing through both the strings*/ return dp[len1][len2]; } // edit distance problem public static int editDistance(String s1, String s2) { int[][] storage = new int[s1.length() + 1][s2.length() + 1]; return editDistance(s1, s2, storage); } public static int editDistance(String s1, String s2, int[][] storage) { int m = s1.length(); int n = s2.length(); if (storage[m][n] > 0) { return storage[m][n]; } if (m == 0) { storage[m][n] = n; return storage[m][n]; } if (n == 0) { storage[m][n] = m; return storage[m][n]; } if (s1.charAt(0) == s2.charAt(0)) { storage[m][n] = editDistance(s1.substring(1), s2.substring(1), storage); } else { int op1 = editDistance(s1, s2.substring(1), storage); int op2 = editDistance(s1.substring(1), s2, storage); int op3 = editDistance(s1.substring(1), s2.substring(1), storage); storage[m][n] = 1 + Math.min(op1, Math.min(op2, op3)); } return storage[m][n]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java
src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java
package com.thealgorithms.dynamicprogramming; import java.util.HashMap; import java.util.Map; /** * Implementation of the full Damerau–Levenshtein distance algorithm. * * This algorithm calculates the minimum number of operations required * to transform one string into another. Supported operations are: * insertion, deletion, substitution, and transposition of adjacent characters. * * Unlike the restricted version (OSA), this implementation allows multiple * edits on the same substring, computing the true edit distance. * * Time Complexity: O(n * m * max(n, m)) * Space Complexity: O(n * m) */ public final class DamerauLevenshteinDistance { private DamerauLevenshteinDistance() { // Utility class } /** * Computes the full Damerau–Levenshtein distance between two strings. * * @param s1 the first string * @param s2 the second string * @return the minimum edit distance between the two strings * @throws IllegalArgumentException if either input string is null */ public static int distance(String s1, String s2) { validateInputs(s1, s2); int n = s1.length(); int m = s2.length(); Map<Character, Integer> charLastPosition = buildCharacterMap(s1, s2); int[][] dp = initializeTable(n, m); fillTable(s1, s2, dp, charLastPosition); return dp[n + 1][m + 1]; } /** * Validates that both input strings are not null. * * @param s1 the first string to validate * @param s2 the second string to validate * @throws IllegalArgumentException if either string is null */ private static void validateInputs(String s1, String s2) { if (s1 == null || s2 == null) { throw new IllegalArgumentException("Input strings must not be null."); } } /** * Builds a character map containing all unique characters from both strings. * Each character is initialized with a position value of 0. * * This map is used to track the last occurrence position of each character * during the distance computation, which is essential for handling transpositions. * * @param s1 the first string * @param s2 the second string * @return a map containing all unique characters from both strings, initialized to 0 */ private static Map<Character, Integer> buildCharacterMap(String s1, String s2) { Map<Character, Integer> charMap = new HashMap<>(); for (char c : s1.toCharArray()) { charMap.putIfAbsent(c, 0); } for (char c : s2.toCharArray()) { charMap.putIfAbsent(c, 0); } return charMap; } /** * Initializes the dynamic programming table for the algorithm. * * The table has dimensions (n+2) x (m+2) where n and m are the lengths * of the input strings. The extra rows and columns are used to handle * the transposition operation correctly. * * The first row and column are initialized with the maximum possible distance, * while the second row and column represent the base case of transforming * from an empty string. * * @param n the length of the first string * @param m the length of the second string * @return an initialized DP table ready for computation */ private static int[][] initializeTable(int n, int m) { int maxDist = n + m; int[][] dp = new int[n + 2][m + 2]; dp[0][0] = maxDist; for (int i = 0; i <= n; i++) { dp[i + 1][0] = maxDist; dp[i + 1][1] = i; } for (int j = 0; j <= m; j++) { dp[0][j + 1] = maxDist; dp[1][j + 1] = j; } return dp; } /** * Fills the dynamic programming table by computing the minimum edit distance * for each substring pair. * * This method implements the core algorithm logic, iterating through both strings * and computing the minimum cost of transforming substrings. It considers all * four operations: insertion, deletion, substitution, and transposition. * * The character position map is updated as we progress through the first string * to enable efficient transposition cost calculation. * * @param s1 the first string * @param s2 the second string * @param dp the dynamic programming table to fill * @param charLastPosition map tracking the last position of each character in s1 */ private static void fillTable(String s1, String s2, int[][] dp, Map<Character, Integer> charLastPosition) { int n = s1.length(); int m = s2.length(); for (int i = 1; i <= n; i++) { int lastMatchCol = 0; for (int j = 1; j <= m; j++) { char char1 = s1.charAt(i - 1); char char2 = s2.charAt(j - 1); int lastMatchRow = charLastPosition.get(char2); int cost = (char1 == char2) ? 0 : 1; if (char1 == char2) { lastMatchCol = j; } dp[i + 1][j + 1] = computeMinimumCost(dp, i, j, lastMatchRow, lastMatchCol, cost); } charLastPosition.put(s1.charAt(i - 1), i); } } /** * Computes the minimum cost among all possible operations at the current position. * * This method evaluates four possible operations: * 1. Substitution: replace character at position i with character at position j * 2. Insertion: insert character from s2 at position j * 3. Deletion: delete character from s1 at position i * 4. Transposition: swap characters that have been seen before * * The transposition cost accounts for the gap between the current position * and the last position where matching characters were found. * * @param dp the dynamic programming table * @param i the current position in the first string (1-indexed in the DP table) * @param j the current position in the second string (1-indexed in the DP table) * @param lastMatchRow the row index where the current character of s2 last appeared in s1 * @param lastMatchCol the column index where the current character of s1 last matched in s2 * @param cost the substitution cost (0 if characters match, 1 otherwise) * @return the minimum cost among all operations */ private static int computeMinimumCost(int[][] dp, int i, int j, int lastMatchRow, int lastMatchCol, int cost) { int substitution = dp[i][j] + cost; int insertion = dp[i + 1][j] + 1; int deletion = dp[i][j + 1] + 1; int transposition = dp[lastMatchRow][lastMatchCol] + i - lastMatchRow - 1 + 1 + j - lastMatchCol - 1; return Math.min(Math.min(substitution, insertion), Math.min(deletion, transposition)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java
src/main/java/com/thealgorithms/dynamicprogramming/WildcardMatching.java
package com.thealgorithms.dynamicprogramming; /** * * Author: Janmesh Singh * Github: https://github.com/janmeshjs * Problem Statement: To determine if the pattern matches the text. * The pattern can include two special wildcard characters: * ' ? ': Matches any single character. * ' * ': Matches zero or more of any character sequence. * * Use DP to return True if the pattern matches the entire text and False otherwise * */ public final class WildcardMatching { private WildcardMatching() { } public static boolean isMatch(String text, String pattern) { int m = text.length(); int n = pattern.length(); // Create a DP table to store intermediate results boolean[][] dp = new boolean[m + 1][n + 1]; // Base case: an empty pattern matches an empty text dp[0][0] = true; // Handle patterns starting with '*' for (int j = 1; j <= n; j++) { if (pattern.charAt(j - 1) == '*') { dp[0][j] = dp[0][j - 1]; } } // Fill the DP table for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { char textChar = text.charAt(i - 1); char patternChar = pattern.charAt(j - 1); if (patternChar == textChar || patternChar == '?') { dp[i][j] = dp[i - 1][j - 1]; } else if (patternChar == '*') { // '*' can match zero or more characters dp[i][j] = dp[i - 1][j] || dp[i][j - 1]; } else { dp[i][j] = false; } } } // The result is in the bottom-right cell of the DP table return dp[m][n]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java
src/main/java/com/thealgorithms/dynamicprogramming/MinimumSumPartition.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; /* Given an array of non-negative integers , partition the array in two subset that difference in sum of elements for both subset minimum. Return the minimum difference in sum of these subsets you can achieve. Input: array[] = {1, 6, 11, 4} Output: 0 Explanation: Subset1 = {1, 4, 6}, sum of Subset1 = 11 Subset2 = {11}, sum of Subset2 = 11 Input: array[] = {36, 7, 46, 40} Output: 23 Explanation: Subset1 = {7, 46} ; sum of Subset1 = 53 Subset2 = {36, 40} ; sum of Subset2 = 76 */ public final class MinimumSumPartition { private MinimumSumPartition() { } private static void throwIfInvalidInput(final int[] array) { if (Arrays.stream(array).anyMatch(a -> a < 0)) { throw new IllegalArgumentException("Input array should not contain negative number(s)."); } } public static int minimumSumPartition(final int[] array) { throwIfInvalidInput(array); int sum = Arrays.stream(array).sum(); boolean[] dp = new boolean[sum / 2 + 1]; dp[0] = true; // Base case , don't select any element from array // Find the closest sum of subset array that we can achieve which is closest to half of sum of full array int closestPartitionSum = 0; for (int i = 0; i < array.length; i++) { for (int j = sum / 2; j > 0; j--) { if (array[i] <= j) { dp[j] = dp[j] || dp[j - array[i]]; } if (dp[j]) { closestPartitionSum = Math.max(closestPartitionSum, j); } } } /* Difference in sum = Big partition sum - Small partition sum = ( Total sum - Small partition sum) - Small partition sum */ return sum - (2 * closestPartitionSum); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; /** * @author Md Asif Joardar * * Description: The partition problem is a classic problem in computer science * that asks whether a given set can be partitioned into two subsets such that * the sum of elements in each subset is the same. * * Example: * Consider nums = {1, 2, 3} * We can split the array "nums" into two partitions, where each having a sum of 3. * nums1 = {1, 2} * nums2 = {3} * * The time complexity of the solution is O(n × sum) and requires O(n × sum) space */ public final class PartitionProblem { private PartitionProblem() { } /** * Test if a set of integers can be partitioned into two subsets such that the sum of elements * in each subset is the same. * * @param nums the array contains integers. * @return {@code true} if two subset exists, otherwise {@code false}. */ public static boolean partition(int[] nums) { // calculate the sum of all the elements in the array int sum = Arrays.stream(nums).sum(); // it will return true if the sum is even and the array can be divided into two // subarrays/subset with equal sum. and here i reuse the SubsetSum class from dynamic // programming section to check if there is exists a subsetsum into nums[] array same as the // given sum return (sum & 1) == 0 && SubsetSum.subsetSum(nums, sum / 2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
package com.thealgorithms.dynamicprogramming; /** * This class implements Kadane's Algorithm to find the maximum subarray sum * within a given array of integers. The algorithm efficiently computes the maximum * sum of a contiguous subarray in linear time. * * Author: <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> */ public final class KadaneAlgorithm { private KadaneAlgorithm() { } /** * Computes the maximum subarray sum using Kadane's Algorithm and checks * if it matches a predicted answer. * * @param a The input array of integers for which the maximum * subarray sum is to be calculated. * @param predictedAnswer The expected maximum subarray sum to be verified * against the computed sum. * @return true if the computed maximum subarray sum equals the predicted * answer, false otherwise. * * <p>Example:</p> * <pre> * Input: {89, 56, 98, 123, 26, 75, 12, 40, 39, 68, 91} * Output: true if the maximum subarray sum is equal to the * predicted answer. * </pre> * * <p>Algorithmic Complexity:</p> * <ul> * <li>Time Complexity: O(n) - the algorithm iterates through the array once.</li> * <li>Auxiliary Space Complexity: O(1) - only a constant amount of additional space is used.</li> * </ul> */ public static boolean maxSum(int[] a, int predictedAnswer) { int sum = a[0]; int runningSum = 0; for (int k : a) { runningSum += k; sum = Math.max(sum, runningSum); if (runningSum < 0) { runningSum = 0; } } return sum == predictedAnswer; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; /** * Author: Siddhant Swarup Mallick * Github: https://github.com/siddhant2002 * <p> * Problem Description: * A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). * The robot can only move either down or right at any point in time. * The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). * How many possible unique paths are there? * <p> * Program Description: * This program calculates the number of unique paths possible for a robot to reach the bottom-right corner * of an m x n grid using dynamic programming. */ public final class UniquePaths { private UniquePaths() { } /** * Calculates the number of unique paths using a 1D dynamic programming array. * Time complexity O(n*m) * Space complexity O(min(n,m)) * * @param m The number of rows in the grid. * @param n The number of columns in the grid. * @return The number of unique paths. */ public static int uniquePaths(final int m, final int n) { if (m > n) { return uniquePaths(n, m); // Recursive call to handle n > m cases } int[] dp = new int[n]; // Create a 1D array to store unique paths for each column Arrays.fill(dp, 1); // Initialize all values to 1 (one way to reach each cell) for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] = Math.addExact(dp[j], dp[j - 1]); // Update the number of unique paths for each cell } } return dp[n - 1]; // The result is stored in the last column of the array } /** * Calculates the number of unique paths using a 2D dynamic programming array. * Time complexity O(n*m) * Space complexity O(n*m) * * @param m The number of rows in the grid. * @param n The number of columns in the grid. * @return The number of unique paths. */ public static int uniquePaths2(final int m, final int n) { int[][] dp = new int[m][n]; // Create a 2D array to store unique paths for each cell for (int i = 0; i < m; i++) { dp[i][0] = 1; // Initialize the first column to 1 (one way to reach each cell) } for (int j = 0; j < n; j++) { dp[0][j] = 1; // Initialize the first row to 1 (one way to reach each cell) } for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[i][j] = Math.addExact(dp[i - 1][j], dp[i][j - 1]); // Update the number of unique paths for each cell } } return dp[m - 1][n - 1]; // The result is stored in the bottom-right cell of the array } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
package com.thealgorithms.dynamicprogramming; import java.util.HashMap; import java.util.Map; /** * @author Varun Upadhyay (https://github.com/varunu28) */ public final class Fibonacci { private Fibonacci() { } static final Map<Integer, Integer> CACHE = new HashMap<>(); /** * This method finds the nth fibonacci number using memoization technique * * @param n The input n for which we have to determine the fibonacci number * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibMemo(int n) { if (n < 0) { throw new IllegalArgumentException("Input n must be non-negative"); } if (CACHE.containsKey(n)) { return CACHE.get(n); } int f; if (n <= 1) { f = n; } else { f = fibMemo(n - 1) + fibMemo(n - 2); CACHE.put(n, f); } return f; } /** * This method finds the nth fibonacci number using bottom up * * @param n The input n for which we have to determine the fibonacci number * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibBotUp(int n) { if (n < 0) { throw new IllegalArgumentException("Input n must be non-negative"); } Map<Integer, Integer> fib = new HashMap<>(); for (int i = 0; i <= n; i++) { int f; if (i <= 1) { f = i; } else { f = fib.get(i - 1) + fib.get(i - 2); } fib.put(i, f); } return fib.get(n); } /** * This method finds the nth fibonacci number using bottom up * * @param n The input n for which we have to determine the fibonacci number * Outputs the nth fibonacci number * <p> * This is optimized version of Fibonacci Program. Without using Hashmap and * recursion. It saves both memory and time. Space Complexity will be O(1) * Time Complexity will be O(n) * <p> * Whereas , the above functions will take O(n) Space. * @throws IllegalArgumentException if n is negative * @author Shoaib Rayeen (https://github.com/shoaibrayeen) */ public static int fibOptimized(int n) { if (n < 0) { throw new IllegalArgumentException("Input n must be non-negative"); } if (n == 0) { return 0; } int prev = 0; int res = 1; int next; for (int i = 2; i <= n; i++) { next = prev + res; prev = res; res = next; } return res; } /** * We have only defined the nth Fibonacci number in terms of the two before it. Now, we will * look at Binet's formula to calculate the nth Fibonacci number in constant time. The Fibonacci * terms maintain a ratio called golden ratio denoted by Φ, the Greek character pronounced * ‘phi'. First, let's look at how the golden ratio is calculated: Φ = ( 1 + √5 )/2 * = 1.6180339887... Now, let's look at Binet's formula: Sn = Φⁿ–(– Φ⁻ⁿ)/√5 We first calculate * the squareRootof5 and phi and store them in variables. Later, we apply Binet's formula to get * the required term. Time Complexity will be O(1) * @param n The input n for which we have to determine the fibonacci number * Outputs the nth fibonacci number * @throws IllegalArgumentException if n is negative */ public static int fibBinet(int n) { if (n < 0) { throw new IllegalArgumentException("Input n must be non-negative"); } double squareRootOf5 = Math.sqrt(5); double phi = (1 + squareRootOf5) / 2; return (int) ((Math.pow(phi, n) - Math.pow(-phi, -n)) / squareRootOf5); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java
src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java
package com.thealgorithms.dynamicprogramming; import com.thealgorithms.datastructures.graphs.UndirectedAdjacencyListGraph; /** * This class implements the algorithm for calculating the maximum weighted matching in a tree. * The tree is represented as an undirected graph with weighted edges. * * Problem Description: * Given an undirected tree G = (V, E) with edge weights γ: E → N and a root r ∈ V, * the goal is to find a maximum weight matching M ⊆ E such that no two edges in M * share a common vertex. The sum of the weights of the edges in M, ∑ e∈M γ(e), should be maximized. * For more Information: <a href="https://en.wikipedia.org/wiki/Matching_(graph_theory)">Matching (graph theory)</a> * * @author <a href="https://github.com/DenizAltunkapan">Deniz Altunkapan</a> */ public class TreeMatching { private UndirectedAdjacencyListGraph graph; private int[][] dp; /** * Constructor that initializes the graph and the DP table. * * @param graph The graph that represents the tree and is used for the matching algorithm. */ public TreeMatching(UndirectedAdjacencyListGraph graph) { this.graph = graph; this.dp = new int[graph.size()][2]; } /** * Calculates the maximum weighted matching for the tree, starting from the given root node. * * @param root The index of the root node of the tree. * @param parent The index of the parent node (used for recursion). * @return The maximum weighted matching for the tree, starting from the root node. * */ public int getMaxMatching(int root, int parent) { if (root < 0 || root >= graph.size()) { throw new IllegalArgumentException("Invalid root: " + root); } maxMatching(root, parent); return Math.max(dp[root][0], dp[root][1]); } /** * Recursively computes the maximum weighted matching for a node, assuming that the node * can either be included or excluded from the matching. * * @param node The index of the current node for which the matching is calculated. * @param parent The index of the parent node (to avoid revisiting the parent node during recursion). */ private void maxMatching(int node, int parent) { dp[node][0] = 0; dp[node][1] = 0; int sumWithoutEdge = 0; for (int adjNode : graph.getNeighbors(node)) { if (adjNode == parent) { continue; } maxMatching(adjNode, node); sumWithoutEdge += Math.max(dp[adjNode][0], dp[adjNode][1]); } dp[node][0] = sumWithoutEdge; for (int adjNode : graph.getNeighbors(node)) { if (adjNode == parent) { continue; } int weight = graph.getEdgeWeight(node, adjNode); dp[node][1] = Math.max(dp[node][1], sumWithoutEdge - Math.max(dp[adjNode][0], dp[adjNode][1]) + dp[adjNode][0] + weight); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
src/main/java/com/thealgorithms/dynamicprogramming/KnapsackMemoization.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; /** * Recursive Solution for 0-1 knapsack with memoization * This method is basically an extension to the recursive approach so that we * can overcome the problem of calculating redundant cases and thus increased * complexity. We can solve this problem by simply creating a 2-D array that can * store a particular state (n, w) if we get it the first time. */ public class KnapsackMemoization { int knapSack(int capacity, int[] weights, int[] profits, int numOfItems) { // Declare the table dynamically int[][] dpTable = new int[numOfItems + 1][capacity + 1]; // Loop to initially fill the table with -1 for (int[] table : dpTable) { Arrays.fill(table, -1); } return solveKnapsackRecursive(capacity, weights, profits, numOfItems, dpTable); } // Returns the value of maximum profit using recursive approach int solveKnapsackRecursive(int capacity, int[] weights, int[] profits, int numOfItems, int[][] dpTable) { // Base condition if (numOfItems == 0 || capacity == 0) { return 0; } if (dpTable[numOfItems][capacity] != -1) { return dpTable[numOfItems][capacity]; } if (weights[numOfItems - 1] > capacity) { // Store the value of function call stack in table dpTable[numOfItems][capacity] = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable); } else { // case 1. include the item, if it is less than the capacity final int includeCurrentItem = profits[numOfItems - 1] + solveKnapsackRecursive(capacity - weights[numOfItems - 1], weights, profits, numOfItems - 1, dpTable); // case 2. exclude the item if it is more than the capacity final int excludeCurrentItem = solveKnapsackRecursive(capacity, weights, profits, numOfItems - 1, dpTable); // Store the value of function call stack in table and return dpTable[numOfItems][capacity] = Math.max(includeCurrentItem, excludeCurrentItem); } return dpTable[numOfItems][capacity]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
package com.thealgorithms.dynamicprogramming; import java.util.Scanner; /** * This file contains an implementation of finding the nth CATALAN NUMBER using * dynamic programming : <a href="https://en.wikipedia.org/wiki/Catalan_number">Wikipedia</a> * * Time Complexity: O(n^2) Space Complexity: O(n) * * @author <a href="https://github.com/amritesh19">AMRITESH ANAND</a> */ public final class CatalanNumber { private CatalanNumber() { } /** * This method finds the nth Catalan number * * @param n input n which determines the nth Catalan number n should be less * than equal to 50 as 50th Catalan number is 6,533,841,209,031,609,592 for * n > 50, BigInteger class should be used instead long * * @return catalanArray[n] the nth Catalan number */ static long findNthCatalan(int n) { // Array to store the results of subproblems i.e Catalan numbers from [1...n-1] long[] catalanArray = new long[n + 1]; // Initialising C₀ = 1 and C₁ = 1 catalanArray[0] = 1; catalanArray[1] = 1; /* * The Catalan numbers satisfy the recurrence relation C₀=1 and Cn = Σ * (Ci * Cn-1-i), i = 0 to n-1 , n > 0 */ for (int i = 2; i <= n; i++) { catalanArray[i] = 0; for (int j = 0; j < i; j++) { catalanArray[i] += catalanArray[j] * catalanArray[i - j - 1]; } } return catalanArray[n]; } // Main method public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the number n to find nth Catalan number (n <= 50)"); int n = sc.nextInt(); System.out.println(n + "th Catalan number is " + findNthCatalan(n)); sc.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MaximumProductSubarray.java
src/main/java/com/thealgorithms/dynamicprogramming/MaximumProductSubarray.java
package com.thealgorithms.dynamicprogramming; /** * The MaximumProductSubarray class implements the algorithm to find the * maximum product of a contiguous subarray within a given array of integers. * * <p>Given an array of integers (which may contain positive numbers, negative * numbers, and zeros), this algorithm finds the contiguous subarray that has * the largest product. The algorithm handles negative numbers efficiently by * tracking both maximum and minimum products, since a negative number can turn * a minimum product into a maximum product.</p> * * <p>This implementation uses a dynamic programming approach that runs in O(n) * time complexity and O(1) space complexity, making it highly efficient for * large arrays.</p> */ public final class MaximumProductSubarray { private MaximumProductSubarray() { // Prevent instantiation } /** * Finds the maximum product of any contiguous subarray in the given array. * * @param nums an array of integers which may contain positive, negative, * and zero values. * @return the maximum product of a contiguous subarray. Returns 0 if the * array is null or empty. */ public static int maxProduct(int[] nums) { if (nums == null || nums.length == 0) { return 0; } long maxProduct = nums[0]; long currentMax = nums[0]; long currentMin = nums[0]; for (int i = 1; i < nums.length; i++) { // Swap currentMax and currentMin if current number is negative if (nums[i] < 0) { long temp = currentMax; currentMax = currentMin; currentMin = temp; } // Update currentMax and currentMin currentMax = Math.max(nums[i], currentMax * nums[i]); currentMin = Math.min(nums[i], currentMin * nums[i]); // Update global max product maxProduct = Math.max(maxProduct, currentMax); } return (int) maxProduct; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
src/main/java/com/thealgorithms/dynamicprogramming/BoardPath.java
package com.thealgorithms.dynamicprogramming; public final class BoardPath { private BoardPath() { } /** * Recursive solution without memoization * * @param start - the current position * @param end - the target position * @return the number of ways to reach the end from the start */ public static int bpR(int start, int end) { if (start == end) { return 1; } else if (start > end) { return 0; } int count = 0; for (int dice = 1; dice <= 6; dice++) { count += bpR(start + dice, end); } return count; } /** * Recursive solution with memoization * * @param curr - the current position * @param end - the target position * @param strg - memoization array * @return the number of ways to reach the end from the start */ public static int bpRS(int curr, int end, int[] strg) { if (curr == end) { return 1; } else if (curr > end) { return 0; } if (strg[curr] != 0) { return strg[curr]; } int count = 0; for (int dice = 1; dice <= 6; dice++) { count += bpRS(curr + dice, end, strg); } strg[curr] = count; return count; } /** * Iterative solution with tabulation * * @param curr - the current position (always starts from 0) * @param end - the target position * @param strg - memoization array * @return the number of ways to reach the end from the start */ public static int bpIS(int curr, int end, int[] strg) { strg[end] = 1; for (int i = end - 1; i >= 0; i--) { int count = 0; for (int dice = 1; dice <= 6 && dice + i <= end; dice++) { count += strg[i + dice]; } strg[i] = count; } return strg[curr]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
package com.thealgorithms.dynamicprogramming; /** * @author Varun Upadhyay (https://github.com/varunu28) */ public final class CoinChange { private CoinChange() { } /** * This method finds the number of combinations of getting change for a * given amount and change coins * * @param coins The list of coins * @param amount The amount for which we need to find the change Finds the * number of combinations of change */ public static int change(int[] coins, int amount) { int[] combinations = new int[amount + 1]; combinations[0] = 1; for (int coin : coins) { for (int i = coin; i < amount + 1; i++) { combinations[i] += combinations[i - coin]; } } return combinations[amount]; } /** * This method finds the minimum number of coins needed for a given amount. * * @param coins The list of coins * @param amount The amount for which we need to find the minimum number of * coins. Finds the minimum number of coins that make a given value. */ public static int minimumCoins(int[] coins, int amount) { // minimumCoins[i] will store the minimum coins needed for amount i int[] minimumCoins = new int[amount + 1]; minimumCoins[0] = 0; for (int i = 1; i <= amount; i++) { minimumCoins[i] = Integer.MAX_VALUE; } for (int i = 1; i <= amount; i++) { for (int coin : coins) { if (coin <= i) { int subRes = minimumCoins[i - coin]; if (subRes != Integer.MAX_VALUE && subRes + 1 < minimumCoins[i]) { minimumCoins[i] = subRes + 1; } } } } return minimumCoins[amount]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java
src/main/java/com/thealgorithms/dynamicprogramming/AssignmentUsingBitmask.java
package com.thealgorithms.dynamicprogramming; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * The AssignmentUsingBitmask class is used to calculate the total number of ways * tasks can be distributed among people, given specific constraints on who can perform which tasks. * The approach uses bitmasking and dynamic programming to efficiently solve the problem. * * @author Hardvan */ public final class AssignmentUsingBitmask { private final int totalTasks; private final int[][] dp; private final List<List<Integer>> task; private final int finalMask; /** * Constructor for the AssignmentUsingBitmask class. * * @param taskPerformed a list of lists, where each inner list contains the tasks that a person can perform. * @param total the total number of tasks. */ public AssignmentUsingBitmask(List<List<Integer>> taskPerformed, int total) { this.totalTasks = total; this.dp = new int[1 << taskPerformed.size()][total + 1]; for (int[] row : dp) { Arrays.fill(row, -1); } this.task = new ArrayList<>(totalTasks + 1); for (int i = 0; i <= totalTasks; i++) { this.task.add(new ArrayList<>()); } // Final mask to check if all persons are included this.finalMask = (1 << taskPerformed.size()) - 1; // Fill the task list for (int i = 0; i < taskPerformed.size(); i++) { for (int j : taskPerformed.get(i)) { this.task.get(j).add(i); } } } /** * Counts the ways to assign tasks until the given task number with the specified mask. * * @param mask the bitmask representing the current state of assignments. * @param taskNo the current task number being processed. * @return the number of ways to assign tasks. */ private int countWaysUntil(int mask, int taskNo) { if (mask == finalMask) { return 1; } if (taskNo > totalTasks) { return 0; } if (dp[mask][taskNo] != -1) { return dp[mask][taskNo]; } int totalWays = countWaysUntil(mask, taskNo + 1); // Assign tasks to all possible persons for (int p : task.get(taskNo)) { // If the person is already assigned a task if ((mask & (1 << p)) != 0) { continue; } totalWays += countWaysUntil(mask | (1 << p), taskNo + 1); } dp[mask][taskNo] = totalWays; return dp[mask][taskNo]; } /** * Counts the total number of ways to distribute tasks among persons. * * @return the total number of ways to distribute tasks. */ public int countNoOfWays() { return countWaysUntil(0, 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Utility class to find the number of unique subsequences that can be * produced from a given string. * * <p> This class contains static methods to compute the unique subsequence count * using dynamic programming and recursion. It ensures that duplicate characters * are not counted multiple times in the subsequences.</p> * * <p> Author: https://github.com/Tuhinm2002 </p> */ public final class UniqueSubsequencesCount { /** * Private constructor to prevent instantiation of this utility class. * This class should only be used in a static context. * * @throws UnsupportedOperationException if attempted to instantiate. */ private UniqueSubsequencesCount() { throw new UnsupportedOperationException("Utility class"); } /** * Finds the number of unique subsequences that can be generated from * the given string. * * <p> This method initializes a dynamic programming (DP) array and invokes * the recursive helper function to compute the subsequence count.</p> * * @param str the input string from which subsequences are generated * @return the total count of unique subsequences */ public static int countSubseq(String str) { // DP array initialized to store intermediate results int[] dp = new int[str.length() + 1]; Arrays.fill(dp, -1); // Calls the recursive function to compute the result return countSubsequences(str, 0, dp); } /** * Recursive helper function to count the number of unique subsequences * starting from the given index. * * <p> Uses a HashSet to avoid counting duplicate characters within * a single subsequence.</p> * * @param st the input string * @param idx the current index from which to calculate subsequences * @param dp dynamic programming array used to memoize results * @return the total number of unique subsequences starting from the * current index */ public static int countSubsequences(String st, int idx, int[] dp) { // Base case: when index exceeds the string length if (idx >= st.length()) { return 0; } // If result is already calculated, return the memoized value if (dp[idx] != -1) { return dp[idx]; } // Set to store characters to avoid duplicates Set<Character> set = new HashSet<>(); int res = 0; // Iterate over the string starting from current index for (int j = idx; j < st.length(); j++) { // If character is already in the set, skip it if (set.contains(st.charAt(j))) { continue; } // Add character to set and recursively calculate subsequences set.add(st.charAt(j)); // 1 for the current subsequence + recursive call for the rest of the string res = 1 + countSubsequences(st, j + 1, dp) + res; } // Memoize the result dp[idx] = res; return dp[idx]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java
src/main/java/com/thealgorithms/dynamicprogramming/DiceThrow.java
package com.thealgorithms.dynamicprogramming; // Given N dice each with M faces, numbered from 1 to M, find the number of ways to get sum X. // X is the summation of values on each face when all the dice are thrown. /* The Naive approach is to find all the possible combinations of values from n dice and keep on counting the results that sum to X. This can be done using recursion. */ // The above recursion solution exhibits overlapping subproblems. /* Hence, storing the results of the solved sub-problems saves time. And it can be done using Dynamic Programming(DP). // Time Complexity: O(m * n * x) where m is number of faces, n is number of dice and x is given sum. Following is implementation of Dynamic Programming approach. */ // Code ----> // Java program to find number of ways to get sum 'x' with 'n' // dice where every dice has 'm' faces final class DP { private DP() { } /* The main function that returns the number of ways to get sum 'x' with 'n' dice and 'm' with m * faces. */ public static long findWays(int m, int n, int x) { /* Create a table to store the results of subproblems. One extra row and column are used for simplicity (Number of dice is directly used as row index and sum is directly used as column index). The entries in 0th row and 0th column are never used. */ long[][] table = new long[n + 1][x + 1]; /* Table entries for only one dice */ for (int j = 1; j <= m && j <= x; j++) { table[1][j] = 1; } /* Fill rest of the entries in table using recursive relation i: number of dice, j: sum */ for (int i = 2; i <= n; i++) { for (int j = 1; j <= x; j++) { for (int k = 1; k < j && k <= m; k++) { table[i][j] += table[i - 1][j - k]; } } } return table[n][x]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java
src/main/java/com/thealgorithms/dynamicprogramming/ShortestCommonSupersequenceLength.java
package com.thealgorithms.dynamicprogramming; /** * Class that provides methods to calculate the length of the shortest * supersequence of two given strings. The shortest supersequence is the smallest string * that contains both given strings as subsequences. */ final class ShortestCommonSupersequenceLength { private ShortestCommonSupersequenceLength() { } /** * Finds the length of the shortest supersequence of two given strings. * The shortest supersequence is defined as the smallest string that contains both * given strings as subsequences. * * @param x The first input string. * @param y The second input string. * @return The length of the shortest supersequence of the two strings. */ static int shortestSuperSequence(String x, String y) { int m = x.length(); int n = y.length(); // find lcs int l = lcs(x, y, m, n); // Result is sum of input string // lengths - length of lcs return m + n - l; } /** * Calculates the length of the longest common subsequence (LCS) between two strings. * The LCS is the longest sequence that can be derived from both strings by deleting some * (or none) of the characters without changing the order of the remaining characters. * * @param x The first input string. * @param y The second input string. * @param m The length of the first input string. * @param n The length of the second input string. * @return The length of the longest common subsequence of the two strings. */ static int lcs(String x, String y, int m, int n) { int[][] lN = new int[m + 1][n + 1]; int i; int j; // Following steps build lN[m + 1][n + 1] // in bottom up fashion. Note that // lN[i][j] contains length of lNCS // of x[0..i - 1]and y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) { lN[i][j] = 0; } else if (x.charAt(i - 1) == y.charAt(j - 1)) { lN[i][j] = lN[i - 1][j - 1] + 1; } else { lN[i][j] = Math.max(lN[i - 1][j], lN[i][j - 1]); } } } // lN[m][n] contains length of LCS // for x[0..n - 1] and y[0..m - 1] return lN[m][n]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
package com.thealgorithms.dynamicprogramming; import java.util.Arrays; /** * 0/1 Knapsack Problem - Dynamic Programming solution. * * This algorithm solves the classic optimization problem where we have n items, * each with a weight and a value. The goal is to maximize the total value * without exceeding the knapsack's weight capacity. * * Time Complexity: O(n * W) * Space Complexity: O(W) * * Example: * values = {60, 100, 120} * weights = {10, 20, 30} * W = 50 * Output: 220 * * @author Arpita * @see <a href="https://en.wikipedia.org/wiki/Knapsack_problem">Knapsack Problem</a> */ public final class Knapsack { private Knapsack() { } /** * Validates the input to ensure correct constraints. */ private static void throwIfInvalidInput(final int weightCapacity, final int[] weights, final int[] values) { if (weightCapacity < 0) { throw new IllegalArgumentException("Weight capacity should not be negative."); } if (weights == null || values == null || weights.length != values.length) { throw new IllegalArgumentException("Weights and values must be non-null and of the same length."); } if (Arrays.stream(weights).anyMatch(w -> w <= 0)) { throw new IllegalArgumentException("Weights must be positive."); } } /** * Solves the 0/1 Knapsack problem using Dynamic Programming (bottom-up approach). * * @param weightCapacity The maximum weight capacity of the knapsack. * @param weights The array of item weights. * @param values The array of item values. * @return The maximum total value achievable without exceeding capacity. */ public static int knapSack(final int weightCapacity, final int[] weights, final int[] values) { throwIfInvalidInput(weightCapacity, weights, values); int[] dp = new int[weightCapacity + 1]; // Fill dp[] array iteratively for (int i = 0; i < values.length; i++) { for (int w = weightCapacity; w >= weights[i]; w--) { dp[w] = Math.max(dp[w], dp[w - weights[i]] + values[i]); } } return dp[weightCapacity]; } /* // Example main method for local testing only. public static void main(String[] args) { int[] values = {60, 100, 120}; int[] weights = {10, 20, 30}; int weightCapacity = 50; int maxValue = knapSack(weightCapacity, weights, values); System.out.println("Maximum value = " + maxValue); // Output: 220 } */ }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
package com.thealgorithms.dynamicprogramming; /** * This class refers to the Optimal Job Scheduling problem with the following constrains: * - precedence relation between the processes * - machine pair dependent transportation delays * * https://en.wikipedia.org/wiki/Optimal_job_scheduling * * @author georgioct@csd.auth.gr */ public class OptimalJobScheduling { private final int numberProcesses; private final int numberMachines; private final int[][] run; private final int[][] transfer; private final int[][] cost; /** * Constructor of the class. * @param numberProcesses ,refers to the number of precedent processes(N) * @param numberMachines ,refers to the number of different machines in our disposal(M) * @param run , N*M matrix refers to the cost of running each process to each machine * @param transfer ,M*M symmetric matrix refers to the transportation delay for each pair of * machines */ public OptimalJobScheduling(int numberProcesses, int numberMachines, int[][] run, int[][] transfer) { this.numberProcesses = numberProcesses; this.numberMachines = numberMachines; this.run = run; this.transfer = transfer; this.cost = new int[numberProcesses][numberMachines]; } /** * Function which computes the cost of process scheduling to a number of VMs. */ public void execute() { this.calculateCost(); this.showResults(); } /** * Function which computes the cost of running each Process to each and every Machine */ private void calculateCost() { for (int i = 0; i < numberProcesses; i++) { // for each Process for (int j = 0; j < numberMachines; j++) { // for each Machine cost[i][j] = runningCost(i, j); } } } /** * Function which returns the minimum cost of running a certain Process to a certain Machine.In * order for the Machine to execute the Process ,he requires the output of the previously * executed Process, which may have been executed to the same Machine or some other.If the * previous Process has been executed to another Machine,we have to transfer her result, which * means extra cost for transferring the data from one Machine to another(if the previous * Process has been executed to the same Machine, there is no transport cost). * * @param process ,refers to the Process * @param machine ,refers to the Machine * @return the minimum cost of executing the process to the certain machine. */ private int runningCost(int process, int machine) { if (process == 0) { // refers to the first process,which does not require for a previous one // to have been executed return run[process][machine]; } else { int[] runningCosts = new int[numberMachines]; // stores the costs of executing our Process depending on // the Machine the previous one was executed for (int k = 0; k < numberMachines; k++) { // computes the cost of executing the previous // process to each and every Machine runningCosts[k] = cost[process - 1][k] + transfer[k][machine] + run[process][machine]; // transferring the result to our Machine and executing // the Process to our Machine } return findMin(runningCosts); // returns the minimum running cost } } /** * Function used in order to return the minimum Cost. * @param costArr ,an Array of size M which refers to the costs of executing a Process to each * Machine * @return the minimum cost */ private int findMin(int[] costArr) { int min = 0; for (int i = 1; i < costArr.length; i++) { if (costArr[i] < costArr[min]) { min = i; } } return costArr[min]; } /** * Method used in order to present the overall costs. */ private void showResults() { for (int i = 0; i < numberProcesses; i++) { for (int j = 0; j < numberMachines; j++) { System.out.print(cost[i][j]); System.out.print(" "); } System.out.println(); } System.out.println(); } /** * Getter for the running Cost of i process on j machine. */ public int getCost(int process, int machine) { return cost[process][machine]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
package com.thealgorithms.dynamicprogramming; /** * The WineProblem class provides a solution to the wine selling problem. * Given a collection of N wines with different prices, the objective is to maximize profit by selling * one wine each year, considering the constraint that only the leftmost or rightmost wine can be sold * at any given time. * * The price of the ith wine is pi, and the selling price increases by a factor of the year in which * it is sold. This class implements three approaches to solve the problem: * * 1. **Recursion**: A straightforward recursive method that computes the maximum profit. * - Time Complexity: O(2^N) * - Space Complexity: O(N) due to recursive calls. * * 2. **Top-Down Dynamic Programming (Memoization)**: This approach caches the results of subproblems * to avoid redundant computations. * - Time Complexity: O(N^2) * - Space Complexity: O(N^2) for the storage of results and O(N) for recursion stack. * * 3. **Bottom-Up Dynamic Programming (Tabulation)**: This method builds a table iteratively to * compute the maximum profit for all possible subproblems. * - Time Complexity: O(N^2) * - Space Complexity: O(N^2) for the table. */ public final class WineProblem { private WineProblem() { } /** * Calculate maximum profit using recursion. * * @param arr Array of wine prices. * @param si Start index of the wine to consider. * @param ei End index of the wine to consider. * @return Maximum profit obtainable by selling the wines. */ public static int wpRecursion(int[] arr, int si, int ei) { int n = arr.length; int year = (n - (ei - si + 1)) + 1; if (si == ei) { return arr[si] * year; } int start = wpRecursion(arr, si + 1, ei) + arr[si] * year; int end = wpRecursion(arr, si, ei - 1) + arr[ei] * year; return Math.max(start, end); } /** * Calculate maximum profit using top-down dynamic programming with memoization. * * @param arr Array of wine prices. * @param si Start index of the wine to consider. * @param ei End index of the wine to consider. * @param strg 2D array to store results of subproblems. * @return Maximum profit obtainable by selling the wines. */ public static int wptd(int[] arr, int si, int ei, int[][] strg) { int n = arr.length; int year = (n - (ei - si + 1)) + 1; if (si == ei) { return arr[si] * year; } if (strg[si][ei] != 0) { return strg[si][ei]; } int start = wptd(arr, si + 1, ei, strg) + arr[si] * year; int end = wptd(arr, si, ei - 1, strg) + arr[ei] * year; int ans = Math.max(start, end); strg[si][ei] = ans; return ans; } /** * Calculate maximum profit using bottom-up dynamic programming with tabulation. * * @param arr Array of wine prices. * @throws IllegalArgumentException if the input array is null or empty. * @return Maximum profit obtainable by selling the wines. */ public static int wpbu(int[] arr) { if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Input array cannot be null or empty."); } int n = arr.length; int[][] strg = new int[n][n]; for (int slide = 0; slide <= n - 1; slide++) { for (int si = 0; si <= n - slide - 1; si++) { int ei = si + slide; int year = (n - (ei - si + 1)) + 1; if (si == ei) { strg[si][ei] = arr[si] * year; } else { int start = strg[si + 1][ei] + arr[si] * year; int end = strg[si][ei - 1] + arr[ei] * year; strg[si][ei] = Math.max(start, end); } } } return strg[0][n - 1]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java
src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java
package com.thealgorithms.dynamicprogramming; /** * The Needleman–Wunsch algorithm performs global sequence alignment between two strings. * It computes the optimal alignment score using dynamic programming, * given a scoring scheme for matches, mismatches, and gaps. * * Time Complexity: O(n * m) * Space Complexity: O(n * m) */ public final class NeedlemanWunsch { private NeedlemanWunsch() { // Utility Class } /** * Computes the Needleman–Wunsch global alignment score between two strings. * * @param s1 the first string * @param s2 the second string * @param matchScore score for a character match * @param mismatchPenalty penalty for a mismatch (should be negative) * @param gapPenalty penalty for inserting a gap (should be negative) * @return the optimal alignment score */ public static int align(String s1, String s2, int matchScore, int mismatchPenalty, int gapPenalty) { if (s1 == null || s2 == null) { throw new IllegalArgumentException("Input strings must not be null."); } int n = s1.length(); int m = s2.length(); int[][] dp = new int[n + 1][m + 1]; // Initialize gap penalties for first row and column for (int i = 0; i <= n; i++) { dp[i][0] = i * gapPenalty; } for (int j = 0; j <= m; j++) { dp[0][j] = j * gapPenalty; } // Fill the DP matrix for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int matchOrMismatch = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? matchScore : mismatchPenalty; dp[i][j] = Math.max(Math.max(dp[i - 1][j - 1] + matchOrMismatch, // match/mismatch dp[i - 1][j] + gapPenalty // deletion (gap in s2) ), dp[i][j - 1] + gapPenalty // insertion (gap in s1) ); } } return dp[n][m]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java
src/main/java/com/thealgorithms/dynamicprogramming/SubsetSumSpaceOptimized.java
package com.thealgorithms.dynamicprogramming; /** * Utility class for solving the Subset Sum problem using a space-optimized dynamic programming approach. * * <p>This algorithm determines whether any subset of a given array sums up to a specific target value.</p> * * <p><b>Time Complexity:</b> O(n * sum)</p> * <p><b>Space Complexity:</b> O(sum)</p> */ public final class SubsetSumSpaceOptimized { private SubsetSumSpaceOptimized() { } /** * Determines whether there exists a subset of the given array that adds up to the specified sum. * This method uses a space-optimized dynamic programming approach with a 1D boolean array. * * @param nums The array of non-negative integers * @param targetSum The desired subset sum * @return {@code true} if such a subset exists, {@code false} otherwise */ public static boolean isSubsetSum(int[] nums, int targetSum) { if (targetSum < 0) { return false; // Subset sum can't be negative } boolean[] dp = new boolean[targetSum + 1]; dp[0] = true; // Empty subset always sums to 0 for (int number : nums) { for (int j = targetSum; j >= number; j--) { dp[j] = dp[j] || dp[j - number]; } } return dp[targetSum]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
src/main/java/com/thealgorithms/dynamicprogramming/BruteForceKnapsack.java
package com.thealgorithms.dynamicprogramming; /** * A naive recursive implementation of the 0-1 Knapsack problem. * * <p>The 0-1 Knapsack problem is a classic optimization problem where you are * given a set of items, each with a weight and a value, and a knapsack with a * fixed capacity. The goal is to determine the maximum value that can be * obtained by selecting a subset of the items such that the total weight does * not exceed the knapsack's capacity. Each item can either be included (1) or * excluded (0), hence the name "0-1" Knapsack.</p> * * <p>This class provides a brute-force recursive approach to solving the * problem. It evaluates all possible combinations of items to find the optimal * solution, but this approach has exponential time complexity and is not * suitable for large input sizes.</p> * * <p><b>Time Complexity:</b> O(2^n), where n is the number of items.</p> * * <p><b>Space Complexity:</b> O(n), due to the recursive function call stack.</p> */ public final class BruteForceKnapsack { private BruteForceKnapsack() { } /** * Solves the 0-1 Knapsack problem using a recursive brute-force approach. * * @param w the total capacity of the knapsack * @param wt an array where wt[i] represents the weight of the i-th item * @param val an array where val[i] represents the value of the i-th item * @param n the number of items available for selection * @return the maximum value that can be obtained with the given capacity * * <p>The function uses recursion to explore all possible subsets of items. * For each item, it has two choices: either include it in the knapsack * (if it fits) or exclude it. It returns the maximum value obtainable * through these two choices.</p> * * <p><b>Base Cases:</b> * <ul> * <li>If no items are left (n == 0), the maximum value is 0.</li> * <li>If the knapsack's remaining capacity is 0 (w == 0), no more items can * be included, and the value is 0.</li> * </ul></p> * * <p><b>Recursive Steps:</b> * <ul> * <li>If the weight of the n-th item exceeds the current capacity, it is * excluded from the solution, and the function proceeds with the remaining * items.</li> * <li>Otherwise, the function considers two possibilities: include the n-th * item or exclude it, and returns the maximum value of these two scenarios.</li> * </ul></p> */ static int knapSack(int w, int[] wt, int[] val, int n) { if (n == 0 || w == 0) { return 0; } if (wt[n - 1] > w) { return knapSack(w, wt, val, n - 1); } else { return Math.max(knapSack(w, wt, val, n - 1), val[n - 1] + knapSack(w - wt[n - 1], wt, val, n - 1)); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
src/main/java/com/thealgorithms/dynamicprogramming/CountFriendsPairing.java
package com.thealgorithms.dynamicprogramming; /** * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> * In mathematics, the Golomb sequence is a non-decreasing integer sequence where n-th term is equal * to number of times n appears in the sequence. * <a href="https://en.wikipedia.org/wiki/Golomb_sequence">Wikipedia</a> * Program description - To find the Golomb sequence upto n */ public final class CountFriendsPairing { private CountFriendsPairing() { } public static boolean countFriendsPairing(int n, int[] a) { int[] dp = new int[n + 1]; // array of n+1 size is created dp[0] = 1; // since 1st index position value is fixed so it's marked as 1 for (int i = 1; i < n; i++) { dp[i] = 1 + dp[i - dp[dp[i - 1]]]; // formula for ith golomb sequence is dp(i) = 1 + dp(i – dp(dp(i - 1))) } for (int i = 1; i < n; i++) { if (a[i - 1] != dp[i]) { return false; // checks whether the calculated answer matches with the expected answer } } return true; // returns true if calculated answer matches with the expected answer } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
src/main/java/com/thealgorithms/dynamicprogramming/SubsetCount.java
package com.thealgorithms.dynamicprogramming; /** * Find the number of subsets present in the given array with a sum equal to target. * Based on Solution discussed on * <a href="https://stackoverflow.com/questions/22891076/count-number-of-subsets-with-sum-equal-to-k">StackOverflow</a> * @author <a href="https://github.com/samratpodder">Samrat Podder</a> */ public final class SubsetCount { private SubsetCount() { } /** * Dynamic Programming Implementation. * Method to find out the number of subsets present in the given array with a sum equal to * target. Time Complexity is O(n*target) and Space Complexity is O(n*target) * @param arr is the input array on which subsets are to searched * @param target is the sum of each element of the subset taken together * */ public static int getCount(int[] arr, int target) { /* * Base Cases - If target becomes zero, we have reached the required sum for the subset * If we reach the end of the array arr then, either if target==arr[end], then we add one to * the final count Otherwise we add 0 to the final count */ int n = arr.length; int[][] dp = new int[n][target + 1]; for (int i = 0; i < n; i++) { dp[i][0] = 1; } if (arr[0] <= target) { dp[0][arr[0]] = 1; } for (int t = 1; t <= target; t++) { for (int idx = 1; idx < n; idx++) { int notpick = dp[idx - 1][t]; int pick = 0; if (arr[idx] <= t) { pick += dp[idx - 1][target - t]; } dp[idx][target] = pick + notpick; } } return dp[n - 1][target]; } /** * This Method is a Space Optimized version of the getCount(int[], int) method and solves the * same problem This approach is a bit better in terms of Space Used Time Complexity is * O(n*target) and Space Complexity is O(target) * @param arr is the input array on which subsets are to searched * @param target is the sum of each element of the subset taken together */ public static int getCountSO(int[] arr, int target) { int n = arr.length; int[] prev = new int[target + 1]; prev[0] = 1; if (arr[0] <= target) { prev[arr[0]] = 1; } for (int ind = 1; ind < n; ind++) { int[] cur = new int[target + 1]; cur[0] = 1; for (int t = 1; t <= target; t++) { int notTaken = prev[t]; int taken = 0; if (arr[ind] <= t) { taken = prev[t - arr[ind]]; } cur[t] = notTaken + taken; } prev = cur; } return prev[target]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestPalindromicSubstring.java
package com.thealgorithms.dynamicprogramming; /** * Class for finding the longest palindromic substring within a given string. * <p> * A palindromic substring is a sequence of characters that reads the same backward as forward. * This class uses a dynamic programming approach to efficiently find the longest palindromic substring. * */ public final class LongestPalindromicSubstring { private LongestPalindromicSubstring() { } public static String lps(String input) { if (input == null || input.isEmpty()) { return input; } boolean[][] arr = new boolean[input.length()][input.length()]; int start = 0; int end = 0; for (int g = 0; g < input.length(); g++) { for (int i = 0, j = g; j < input.length(); i++, j++) { if (g == 0) { arr[i][j] = true; } else if (g == 1) { arr[i][j] = input.charAt(i) == input.charAt(j); } else { arr[i][j] = input.charAt(i) == input.charAt(j) && arr[i + 1][j - 1]; } if (arr[i][j]) { start = i; end = j; } } } return input.substring(start, end + 1); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
src/main/java/com/thealgorithms/dynamicprogramming/SubsetSum.java
package com.thealgorithms.dynamicprogramming; public final class SubsetSum { private SubsetSum() { } /** * Test if a set of integers contains a subset that sums to a given integer. * * @param arr the array containing integers. * @param sum the target sum of the subset. * @return {@code true} if a subset exists that sums to the given value, * otherwise {@code false}. */ public static boolean subsetSum(int[] arr, int sum) { int n = arr.length; // Initialize a single array to store the possible sums boolean[] isSum = new boolean[sum + 1]; // Mark isSum[0] = true since a sum of 0 is always possible with 0 elements isSum[0] = true; // Iterate through each Element in the array for (int i = 0; i < n; i++) { // Traverse the isSum array backwards to prevent overwriting values for (int j = sum; j >= arr[i]; j--) { isSum[j] = isSum[j] || isSum[j - arr[i]]; } } return isSum[sum]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
src/main/java/com/thealgorithms/dynamicprogramming/EggDropping.java
package com.thealgorithms.dynamicprogramming; /** * DynamicProgramming solution for the Egg Dropping Puzzle */ public final class EggDropping { private EggDropping() { } // min trials with n eggs and m floors public static int minTrials(int n, int m) { int[][] eggFloor = new int[n + 1][m + 1]; int result; int x; for (int i = 1; i <= n; i++) { eggFloor[i][0] = 0; // Zero trial for zero floor. eggFloor[i][1] = 1; // One trial for one floor } // j trials for only 1 egg for (int j = 1; j <= m; j++) { eggFloor[1][j] = j; } // Using bottom-up approach in DP for (int i = 2; i <= n; i++) { for (int j = 2; j <= m; j++) { eggFloor[i][j] = Integer.MAX_VALUE; for (x = 1; x <= j; x++) { result = 1 + Math.max(eggFloor[i - 1][x - 1], eggFloor[i][j - x]); // choose min of all values for particular x if (result < eggFloor[i][j]) { eggFloor[i][j] = result; } } } } return eggFloor[n][m]; } public static void main(String[] args) { int n = 2; int m = 4; // result outputs min no. of trials in worst case for n eggs and m floors int result = minTrials(n, m); System.out.println(result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java
src/main/java/com/thealgorithms/dynamicprogramming/Abbreviation.java
package com.thealgorithms.dynamicprogramming; /** * A class that provides a solution to the abbreviation problem. * * Problem: Given two strings, `a` and `b`, determine if string `a` can be * transformed into string `b` by performing the following operations: * 1. Capitalize zero or more of `a`'s lowercase letters (i.e., convert them to uppercase). * 2. Delete any of the remaining lowercase letters from `a`. * * The task is to determine whether it is possible to make string `a` equal to string `b`. * * @author Hardvan */ public final class Abbreviation { private Abbreviation() { } /** * Determines if string `a` can be transformed into string `b` by capitalizing * some of its lowercase letters and deleting the rest. * * @param a The input string which may contain both uppercase and lowercase letters. * @param b The target string containing only uppercase letters. * @return {@code true} if string `a` can be transformed into string `b`, * {@code false} otherwise. * * Time Complexity: O(n * m) where n = length of string `a` and m = length of string `b`. * Space Complexity: O(n * m) due to the dynamic programming table. */ public static boolean abbr(String a, String b) { int n = a.length(); int m = b.length(); boolean[][] dp = new boolean[n + 1][m + 1]; dp[0][0] = true; for (int i = 0; i < n; i++) { for (int j = 0; j <= m; j++) { if (dp[i][j]) { // Case 1: If the current characters match (or can be capitalized to match) if (j < m && Character.toUpperCase(a.charAt(i)) == b.charAt(j)) { dp[i + 1][j + 1] = true; } // Case 2: If the character in `a` is lowercase, we can skip it if (Character.isLowerCase(a.charAt(i))) { dp[i + 1][j] = true; } } } } return dp[n][m]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java
src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java
package com.thealgorithms.dynamicprogramming; import java.util.ArrayList; import java.util.List; /** * This class provides a solution to the "All Construct" problem. * * The problem is to determine all the ways a target string can be constructed * from a given list of substrings. Each substring in the word bank can be used * multiple times, and the order of substrings matters. * * @author Hardvan */ public final class AllConstruct { private AllConstruct() { } /** * Finds all possible ways to construct the target string using substrings * from the given word bank. * Time Complexity: O(n * m * k), where n = length of the target, * m = number of words in wordBank, and k = average length of a word. * * Space Complexity: O(n * m) due to the size of the table storing combinations. * * @param target The target string to construct. * @param wordBank An iterable collection of substrings that can be used to construct the target. * @return A list of lists, where each inner list represents one possible * way of constructing the target string using the given word bank. */ public static List<List<String>> allConstruct(String target, Iterable<String> wordBank) { List<List<List<String>>> table = new ArrayList<>(target.length() + 1); for (int i = 0; i <= target.length(); i++) { table.add(new ArrayList<>()); } table.get(0).add(new ArrayList<>()); for (int i = 0; i <= target.length(); i++) { if (!table.get(i).isEmpty()) { for (String word : wordBank) { if (i + word.length() <= target.length() && target.substring(i, i + word.length()).equals(word)) { List<List<String>> newCombinations = new ArrayList<>(); for (List<String> combination : table.get(i)) { List<String> newCombination = new ArrayList<>(combination); newCombination.add(word); newCombinations.add(newCombination); } table.get(i + word.length()).addAll(newCombinations); } } } } return table.get(target.length()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java
package com.thealgorithms.dynamicprogramming; import java.util.HashMap; @SuppressWarnings({"rawtypes", "unchecked"}) final class LongestArithmeticSubsequence { private LongestArithmeticSubsequence() { } /** * Returns the length of the longest arithmetic subsequence in the given array. * * A sequence seq is arithmetic if seq[i + 1] - seq[i] are all the same value * (for 0 <= i < seq.length - 1). * * @param nums the input array of integers * @return the length of the longest arithmetic subsequence */ public static int getLongestArithmeticSubsequenceLength(int[] nums) { if (nums == null) { throw new IllegalArgumentException("Input array cannot be null"); } if (nums.length <= 1) { return nums.length; } HashMap<Integer, Integer>[] dp = new HashMap[nums.length]; int maxLength = 2; // fill the dp array for (int i = 0; i < nums.length; i++) { dp[i] = new HashMap<>(); for (int j = 0; j < i; j++) { final int diff = nums[i] - nums[j]; dp[i].put(diff, dp[j].getOrDefault(diff, 1) + 1); maxLength = Math.max(maxLength, dp[i].get(diff)); } } return maxLength; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
package com.thealgorithms.dynamicprogramming; /** * Class to find the maximum sum of non-adjacent elements in an array. This * class contains two approaches: one with O(n) space complexity and another * with O(1) space optimization. For more information, refer to * https://takeuforward.org/data-structure/maximum-sum-of-non-adjacent-elements-dp-5/ */ final class MaximumSumOfNonAdjacentElements { private MaximumSumOfNonAdjacentElements() { } /** * Approach 1: Uses a dynamic programming array to store the maximum sum at * each index. Time Complexity: O(n) - where n is the length of the input * array. Space Complexity: O(n) - due to the additional dp array. * @param arr The input array of integers. * @return The maximum sum of non-adjacent elements. */ public static int getMaxSumApproach1(int[] arr) { if (arr.length == 0) { return 0; // Check for empty array } int n = arr.length; int[] dp = new int[n]; // Base case: Maximum sum if only one element is present. dp[0] = arr[0]; for (int ind = 1; ind < n; ind++) { // Case 1: Do not take the current element, carry forward the previous max // sum. int notTake = dp[ind - 1]; // Case 2: Take the current element, add it to the max sum up to two // indices before. int take = arr[ind]; if (ind > 1) { take += dp[ind - 2]; } // Store the maximum of both choices in the dp array. dp[ind] = Math.max(take, notTake); } return dp[n - 1]; } /** * Approach 2: Optimized space complexity approach using two variables instead * of an array. Time Complexity: O(n) - where n is the length of the input * array. Space Complexity: O(1) - as it only uses constant space for two * variables. * @param arr The input array of integers. * @return The maximum sum of non-adjacent elements. */ public static int getMaxSumApproach2(int[] arr) { if (arr.length == 0) { return 0; // Check for empty array } int n = arr.length; // Two variables to keep track of previous two results: // prev1 = max sum up to the last element (n-1) // prev2 = max sum up to the element before last (n-2) int prev1 = arr[0]; // Base case: Maximum sum for the first element. int prev2 = 0; for (int ind = 1; ind < n; ind++) { // Case 1: Do not take the current element, keep the last max sum. int notTake = prev1; // Case 2: Take the current element and add it to the result from two // steps back. int take = arr[ind]; if (ind > 1) { take += prev2; } // Calculate the current maximum sum and update previous values. int current = Math.max(take, notTake); // Shift prev1 and prev2 for the next iteration. prev2 = prev1; prev1 = current; } return prev1; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainMultiplication.java
package com.thealgorithms.dynamicprogramming; import java.util.ArrayList; import java.util.Arrays; /** * The MatrixChainMultiplication class provides functionality to compute the * optimal way to multiply a sequence of matrices. The optimal multiplication * order is determined using dynamic programming, which minimizes the total * number of scalar multiplications required. */ public final class MatrixChainMultiplication { private MatrixChainMultiplication() { } // Matrices to store minimum multiplication costs and split points private static int[][] m; private static int[][] s; private static int[] p; /** * Calculates the optimal order for multiplying a given list of matrices. * * @param matrices an ArrayList of Matrix objects representing the matrices * to be multiplied. * @return a Result object containing the matrices of minimum costs and * optimal splits. */ public static Result calculateMatrixChainOrder(ArrayList<Matrix> matrices) { int size = matrices.size(); m = new int[size + 1][size + 1]; s = new int[size + 1][size + 1]; p = new int[size + 1]; for (int i = 0; i < size + 1; i++) { Arrays.fill(m[i], -1); Arrays.fill(s[i], -1); } for (int i = 0; i < p.length; i++) { p[i] = i == 0 ? matrices.get(i).col() : matrices.get(i - 1).row(); } matrixChainOrder(size); return new Result(m, s); } /** * A helper method that computes the minimum cost of multiplying * the matrices using dynamic programming. * * @param size the number of matrices in the multiplication sequence. */ private static void matrixChainOrder(int size) { for (int i = 1; i < size + 1; i++) { m[i][i] = 0; } for (int l = 2; l < size + 1; l++) { for (int i = 1; i < size - l + 2; i++) { int j = i + l - 1; m[i][j] = Integer.MAX_VALUE; for (int k = i; k < j; k++) { int q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j]; if (q < m[i][j]) { m[i][j] = q; s[i][j] = k; } } } } } /** * The Result class holds the results of the matrix chain multiplication * calculation, including the matrix of minimum costs and split points. */ public static class Result { private final int[][] m; private final int[][] s; /** * Constructs a Result object with the specified matrices of minimum * costs and split points. * * @param m the matrix of minimum multiplication costs. * @param s the matrix of optimal split points. */ public Result(int[][] m, int[][] s) { this.m = m; this.s = s; } /** * Returns the matrix of minimum multiplication costs. * * @return the matrix of minimum multiplication costs. */ public int[][] getM() { return m; } /** * Returns the matrix of optimal split points. * * @return the matrix of optimal split points. */ public int[][] getS() { return s; } } /** * The Matrix class represents a matrix with its dimensions and count. */ public static class Matrix { private final int count; private final int col; private final int row; /** * Constructs a Matrix object with the specified count, number of columns, * and number of rows. * * @param count the identifier for the matrix. * @param col the number of columns in the matrix. * @param row the number of rows in the matrix. */ public Matrix(int count, int col, int row) { this.count = count; this.col = col; this.row = row; } /** * Returns the identifier of the matrix. * * @return the identifier of the matrix. */ public int count() { return count; } /** * Returns the number of columns in the matrix. * * @return the number of columns in the matrix. */ public int col() { return col; } /** * Returns the number of rows in the matrix. * * @return the number of rows in the matrix. */ public int row() { return row; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java
src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java
package com.thealgorithms.dynamicprogramming; /** * The {@code KnapsackZeroOne} provides Recursive solution for the 0/1 Knapsack * problem. Solves by exploring all combinations of items using recursion. No * memoization or dynamic programming optimizations are applied. * * Time Complexity: O(2^n) — explores all subsets. * Space Complexity: O(n) — due to recursive call stack. * * Problem Reference: https://en.wikipedia.org/wiki/Knapsack_problem */ public final class KnapsackZeroOne { private KnapsackZeroOne() { // Prevent instantiation } /** * Solves the 0/1 Knapsack problem using recursion. * * @param values the array containing values of the items * @param weights the array containing weights of the items * @param capacity the total capacity of the knapsack * @param n the number of items * @return the maximum total value achievable within the given weight limit * @throws IllegalArgumentException if input arrays are null, empty, or * lengths mismatch */ public static int compute(final int[] values, final int[] weights, final int capacity, final int n) { if (values == null || weights == null) { throw new IllegalArgumentException("Input arrays cannot be null."); } if (values.length != weights.length) { throw new IllegalArgumentException("Value and weight arrays must be of the same length."); } if (capacity < 0 || n < 0) { throw new IllegalArgumentException("Invalid input: arrays must be non-empty and capacity/n " + "non-negative."); } if (n == 0 || capacity == 0 || values.length == 0) { return 0; } if (weights[n - 1] <= capacity) { final int include = values[n - 1] + compute(values, weights, capacity - weights[n - 1], n - 1); final int exclude = compute(values, weights, capacity, n - 1); return Math.max(include, exclude); } else { return compute(values, weights, capacity, n - 1); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java
src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java
package com.thealgorithms.dynamicprogramming; /** * A utility class that contains the Sum of Subset problem solution using * recursion. * * The Sum of Subset problem determines whether a subset of elements from a * given array sums up to a specific target value. * * Wikipedia: https://en.wikipedia.org/wiki/Subset_sum_problem */ public final class SumOfSubset { private SumOfSubset() { } /** * Determines if there exists a subset of elements in the array `arr` that * adds up to the given `key` value using recursion. * * @param arr The array of integers. * @param num The index of the current element being considered. * @param key The target sum we are trying to achieve. * @return true if a subset of `arr` adds up to `key`, false otherwise. * * This is a recursive solution that checks for two possibilities at * each step: * 1. Include the current element in the subset and check if the * remaining elements can sum up to the remaining target. * 2. Exclude the current element and check if the remaining elements * can sum up to the target without this element. */ public static boolean subsetSum(int[] arr, int num, int key) { if (key == 0) { return true; } if (num < 0 || key < 0) { return false; } boolean include = subsetSum(arr, num - 1, key - arr[num]); boolean exclude = subsetSum(arr, num - 1, key); return include || exclude; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java
src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java
package com.thealgorithms.dynamicprogramming; /** * Smith–Waterman algorithm for local sequence alignment. * Finds the highest scoring local alignment between substrings of two sequences. * * Time Complexity: O(n * m) * Space Complexity: O(n * m) */ public final class SmithWaterman { private SmithWaterman() { // Utility Class } /** * Computes the Smith–Waterman local alignment score between two strings. * * @param s1 first string * @param s2 second string * @param matchScore score for a match * @param mismatchPenalty penalty for mismatch (negative) * @param gapPenalty penalty for insertion/deletion (negative) * @return the maximum local alignment score */ public static int align(String s1, String s2, int matchScore, int mismatchPenalty, int gapPenalty) { if (s1 == null || s2 == null) { throw new IllegalArgumentException("Input strings must not be null."); } int n = s1.length(); int m = s2.length(); int maxScore = 0; int[][] dp = new int[n + 1][m + 1]; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { int matchOrMismatch = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? matchScore : mismatchPenalty; dp[i][j] = Math.max(0, Math.max(Math.max(dp[i - 1][j - 1] + matchOrMismatch, // match/mismatch dp[i - 1][j] + gapPenalty // deletion ), dp[i][j - 1] + gapPenalty // insertion )); if (dp[i][j] > maxScore) { maxScore = dp[i][j]; } } } return maxScore; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestAlternatingSubsequence.java
package com.thealgorithms.dynamicprogramming; /** * Class for finding the length of the longest alternating subsequence in an array. * * <p>An alternating sequence is a sequence of numbers where the elements alternate * between increasing and decreasing. Specifically, a sequence is alternating if its elements * satisfy one of the following relations: * * <ul> * <li>{@code x1 < x2 > x3 < x4 > x5 < ... < xn}</li> * <li>{@code x1 > x2 < x3 > x4 < x5 > ... > xn}</li> * </ul> * * <p>This class provides a method to compute the length of the longest such subsequence * from a given array of integers. */ public final class LongestAlternatingSubsequence { private LongestAlternatingSubsequence() { } /** * Finds the length of the longest alternating subsequence in the given array. * * @param arr an array of integers where the longest alternating subsequence is to be found * @param n the length of the array {@code arr} * @return the length of the longest alternating subsequence * * <p>The method uses dynamic programming to solve the problem. It maintains a 2D array * {@code las} where: * <ul> * <li>{@code las[i][0]} represents the length of the longest alternating subsequence * ending at index {@code i} with the last element being greater than the previous element.</li> * <li>{@code las[i][1]} represents the length of the longest alternating subsequence * ending at index {@code i} with the last element being smaller than the previous element.</li> * </ul> * * <p>The method iterates through the array and updates the {@code las} array based on * whether the current element is greater or smaller than the previous elements. * The result is the maximum value found in the {@code las} array. */ static int alternatingLength(int[] arr, int n) { int[][] las = new int[n][2]; // las = LongestAlternatingSubsequence // Initialize the dp array for (int i = 0; i < n; i++) { las[i][0] = 1; las[i][1] = 1; } int result = 1; // Initialize result // Compute values in a bottom-up manner for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { // If arr[i] is greater than arr[j], update las[i][0] if (arr[j] < arr[i] && las[i][0] < las[j][1] + 1) { las[i][0] = las[j][1] + 1; } // If arr[i] is smaller than arr[j], update las[i][1] if (arr[j] > arr[i] && las[i][1] < las[j][0] + 1) { las[i][1] = las[j][0] + 1; } } // Pick the maximum of both values at index i result = Math.max(result, Math.max(las[i][0], las[i][1])); } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
src/main/java/com/thealgorithms/dynamicprogramming/MatrixChainRecursiveTopDownMemoisation.java
package com.thealgorithms.dynamicprogramming; /** * The MatrixChainRecursiveTopDownMemoisation class implements the matrix-chain * multiplication problem using a top-down recursive approach with memoization. * * <p>Given a chain of matrices A1, A2, ..., An, where matrix Ai has dimensions * pi-1 × pi, this algorithm finds the optimal way to fully parenthesize the * product A1A2...An in a way that minimizes the total number of scalar * multiplications required.</p> * * <p>This implementation uses a memoization technique to store the results of * subproblems, which significantly reduces the number of recursive calls and * improves performance compared to a naive recursive approach.</p> */ public final class MatrixChainRecursiveTopDownMemoisation { private MatrixChainRecursiveTopDownMemoisation() { } /** * Calculates the minimum number of scalar multiplications needed to multiply * a chain of matrices. * * @param p an array of integers representing the dimensions of the matrices. * The length of the array is n + 1, where n is the number of matrices. * @return the minimum number of multiplications required to multiply the chain * of matrices. */ static int memoizedMatrixChain(int[] p) { int n = p.length; int[][] m = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[i][j] = Integer.MAX_VALUE; } } return lookupChain(m, p, 1, n - 1); } /** * A recursive helper method to lookup the minimum number of multiplications * for multiplying matrices from index i to index j. * * @param m the memoization table storing the results of subproblems. * @param p an array of integers representing the dimensions of the matrices. * @param i the starting index of the matrix chain. * @param j the ending index of the matrix chain. * @return the minimum number of multiplications needed to multiply matrices * from i to j. */ static int lookupChain(int[][] m, int[] p, int i, int j) { if (i == j) { m[i][j] = 0; return m[i][j]; } if (m[i][j] < Integer.MAX_VALUE) { return m[i][j]; } else { for (int k = i; k < j; k++) { int q = lookupChain(m, p, i, k) + lookupChain(m, p, k + 1, j) + (p[i - 1] * p[k] * p[j]); if (q < m[i][j]) { m[i][j] = q; } } } return m[i][j]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
package com.thealgorithms.dynamicprogramming; /** * Java program for Boundary fill algorithm. * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ public final class BoundaryFill { private BoundaryFill() { } /** * Get the color at the given co-odrinates of a 2D image * * @param image The image to be filled * @param xCoordinate The x coordinate of which color is to be obtained * @param yCoordinate The y coordinate of which color is to be obtained */ public static int getPixel(int[][] image, int xCoordinate, int yCoordinate) { return image[xCoordinate][yCoordinate]; } /** * Put the color at the given co-odrinates of a 2D image * * @param image The image to be filed * @param xCoordinate The x coordinate at which color is to be filled * @param yCoordinate The y coordinate at which color is to be filled */ public static void putPixel(int[][] image, int xCoordinate, int yCoordinate, int newColor) { image[xCoordinate][yCoordinate] = newColor; } /** * Fill the 2D image with new color * * @param image The image to be filed * @param xCoordinate The x coordinate at which color is to be filled * @param yCoordinate The y coordinate at which color is to be filled * @param newColor The new color which to be filled in the image * @param boundaryColor The old color which is to be replaced in the image */ public static void boundaryFill(int[][] image, int xCoordinate, int yCoordinate, int newColor, int boundaryColor) { if (xCoordinate >= 0 && yCoordinate >= 0 && getPixel(image, xCoordinate, yCoordinate) != newColor && getPixel(image, xCoordinate, yCoordinate) != boundaryColor) { putPixel(image, xCoordinate, yCoordinate, newColor); boundaryFill(image, xCoordinate + 1, yCoordinate, newColor, boundaryColor); boundaryFill(image, xCoordinate - 1, yCoordinate, newColor, boundaryColor); boundaryFill(image, xCoordinate, yCoordinate + 1, newColor, boundaryColor); boundaryFill(image, xCoordinate, yCoordinate - 1, newColor, boundaryColor); boundaryFill(image, xCoordinate + 1, yCoordinate - 1, newColor, boundaryColor); boundaryFill(image, xCoordinate - 1, yCoordinate + 1, newColor, boundaryColor); boundaryFill(image, xCoordinate + 1, yCoordinate + 1, newColor, boundaryColor); boundaryFill(image, xCoordinate - 1, yCoordinate - 1, newColor, boundaryColor); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java
src/main/java/com/thealgorithms/dynamicprogramming/MinimumPathSum.java
package com.thealgorithms.dynamicprogramming; /* Given the following grid with length m and width n: \---\---\---\ (n) \ 1 \ 3 \ 1 \ \---\---\---\ \ 1 \ 5 \ 1 \ \---\---\---\ \ 4 \ 2 \ 1 \ \---\---\---\ (m) Find the path where its sum is the smallest. The Time Complexity of your algorithm should be smaller than or equal to O(mn). The Space Complexity of your algorithm should be smaller than or equal to O(n). You can only move from the top left corner to the down right corner. You can only move one step down or right. EXAMPLE: INPUT: grid = [[1,3,1],[1,5,1],[4,2,1]] OUTPUT: 7 EXPLANATIONS: 1 + 3 + 1 + 1 + 1 = 7 For more information see https://www.geeksforgeeks.org/maximum-path-sum-matrix/ */ public final class MinimumPathSum { private MinimumPathSum() { } public static int minimumPathSum(final int[][] grid) { int numRows = grid.length; int numCols = grid[0].length; if (numCols == 0) { return 0; } int[] dp = new int[numCols]; // Initialize the first element of the dp array dp[0] = grid[0][0]; // Calculate the minimum path sums for the first row for (int col = 1; col < numCols; col++) { dp[col] = dp[col - 1] + grid[0][col]; } // Calculate the minimum path sums for the remaining rows for (int row = 1; row < numRows; row++) { // Update the minimum path sum for the first column dp[0] += grid[row][0]; for (int col = 1; col < numCols; col++) { // Choose the minimum path sum from the left or above dp[col] = Math.min(dp[col - 1], dp[col]) + grid[row][col]; } } // Return the minimum path sum for the last cell in the grid return dp[numCols - 1]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
src/main/java/com/thealgorithms/dynamicprogramming/NewManShanksPrime.java
package com.thealgorithms.dynamicprogramming; /** * The NewManShanksPrime class provides a method to determine whether the nth * New Man Shanks prime matches an expected answer. * * <p>This is based on the New Man Shanks prime sequence defined by the recurrence * relation:</p> * * <pre> * a(n) = 2 * a(n-1) + a(n-2) for n >= 2 * a(0) = 1 * a(1) = 1 * </pre> * * <p>For more information on New Man Shanks primes, please refer to the * <a href="https://en.wikipedia.org/wiki/Newman%E2%80%93Shanks%E2%80%93Williams_prime"> * Wikipedia article</a>.</p> * * <p>Note: The class is designed to be non-instantiable.</p> * * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> */ public final class NewManShanksPrime { private NewManShanksPrime() { } /** * Calculates the nth New Man Shanks prime and checks if it equals the * expected answer. * * @param n the index of the New Man Shanks prime to calculate (0-based). * @param expectedAnswer the expected value of the nth New Man Shanks prime. * @return true if the calculated nth New Man Shanks prime matches the * expected answer; false otherwise. */ public static boolean nthManShanksPrime(int n, int expectedAnswer) { int[] a = new int[n + 1]; a[0] = 1; a[1] = 1; for (int i = 2; i <= n; i++) { a[i] = 2 * a[i - 1] + a[i - 2]; } return a[n] == expectedAnswer; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
src/main/java/com/thealgorithms/dynamicprogramming/ClimbingStairs.java
package com.thealgorithms.dynamicprogramming; /* * A dynamic programming solution for the "Climbing Stairs" problem. * Returns the no. of distinct ways to climb to the top * of a staircase when you can climb either 1 or 2 steps at a time. * * For example, if there are 5 steps, the possible ways to climb the * staircase are: * 1. 1-1-1-1-1 * 2. 1-1-1-2 * 3. 1-2-1-1 * 4. 2-1-1-1 * 5. 2-2-1 * 6. 1-1-2-1 * 7. 1-2-2 * 8. 2-1-2 * Ans: 8 ways */ public final class ClimbingStairs { private ClimbingStairs() { } /** * Calculates the no. of distinct ways to climb a staircase with n steps. * * @param n the no. of steps in the staircase (non-negative integer) * @return the no. of distinct ways to climb to the top * - Returns 0 if n is 0 (no steps to climb). * - Returns 1 if n is 1 (only one way to climb). * - For n > 1, it returns the total no. of ways to climb. */ public static int numberOfWays(int n) { // Base case: if there are no steps or only one step, return n. if (n == 1 || n == 0) { return n; } int prev = 1; // Ways to reach the step before the current one (step 1) int curr = 1; // Ways to reach the current step (step 2) int next; // Total ways to reach the next step for (int i = 2; i <= n; i++) { // step 2 to n next = curr + prev; // Move the pointers to the next step prev = curr; curr = next; } return curr; // Ways to reach the nth step } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
package com.thealgorithms.dynamicprogramming; /** * Given a text and wildcard pattern implement a wildcard pattern matching * algorithm that finds if wildcard is matched with text. The matching should * cover the entire text ?-> matches single characters *-> match the sequence of * characters * * For calculation of Time and Space Complexity. Let N be length of src and M be length of pat * * Memoization vs Tabulation : https://www.geeksforgeeks.org/tabulation-vs-memoization/ * Question Link : https://practice.geeksforgeeks.org/problems/wildcard-pattern-matching/1 */ public final class RegexMatching { private RegexMatching() { } /** * Method 1: Determines if the given source string matches the given pattern using a recursive approach. * This method directly applies recursion to check if the source string matches the pattern, considering * the wildcards '?' and '*'. * * Time Complexity: O(2^(N+M)), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N + M) due to the recursion stack. * * @param src The source string to be matched against the pattern. * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ public static boolean regexRecursion(String src, String pat) { if (src.length() == 0 && pat.length() == 0) { return true; } if (src.length() != 0 && pat.length() == 0) { return false; } if (src.length() == 0 && pat.length() != 0) { for (int i = 0; i < pat.length(); i++) { if (pat.charAt(i) != '*') { return false; } } return true; } char chs = src.charAt(0); char chp = pat.charAt(0); String ros = src.substring(1); String rop = pat.substring(1); boolean ans; if (chs == chp || chp == '?') { ans = regexRecursion(ros, rop); } else if (chp == '*') { boolean blank = regexRecursion(src, rop); boolean multiple = regexRecursion(ros, pat); ans = blank || multiple; } else { ans = false; } return ans; } /** * Method 2: Determines if the given source string matches the given pattern using recursion. * This method utilizes a virtual index for both the source string and the pattern to manage the recursion. * * Time Complexity: O(2^(N+M)) where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N + M) due to the recursion stack. * * @param src The source string to be matched against the pattern. * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @param svidx The current index in the source string. * @param pvidx The current index in the pattern. * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ static boolean regexRecursion(String src, String pat, int svidx, int pvidx) { if (src.length() == svidx && pat.length() == pvidx) { return true; } if (src.length() != svidx && pat.length() == pvidx) { return false; } if (src.length() == svidx && pat.length() != pvidx) { for (int i = pvidx; i < pat.length(); i++) { if (pat.charAt(i) != '*') { return false; } } return true; } char chs = src.charAt(svidx); char chp = pat.charAt(pvidx); boolean ans; if (chs == chp || chp == '?') { ans = regexRecursion(src, pat, svidx + 1, pvidx + 1); } else if (chp == '*') { boolean blank = regexRecursion(src, pat, svidx, pvidx + 1); boolean multiple = regexRecursion(src, pat, svidx + 1, pvidx); ans = blank || multiple; } else { ans = false; } return ans; } /** * Method 3: Determines if the given source string matches the given pattern using top-down dynamic programming (memoization). * This method utilizes memoization to store intermediate results, reducing redundant computations and improving efficiency. * * Time Complexity: O(N * M), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N * M) for the memoization table, plus additional space for the recursion stack. * * @param src The source string to be matched against the pattern. * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @param svidx The current index in the source string. * @param pvidx The current index in the pattern. * @param strg A 2D array used for memoization to store the results of subproblems. * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ public static boolean regexRecursion(String src, String pat, int svidx, int pvidx, int[][] strg) { if (src.length() == svidx && pat.length() == pvidx) { return true; } if (src.length() != svidx && pat.length() == pvidx) { return false; } if (src.length() == svidx && pat.length() != pvidx) { for (int i = pvidx; i < pat.length(); i++) { if (pat.charAt(i) != '*') { return false; } } return true; } if (strg[svidx][pvidx] != 0) { return strg[svidx][pvidx] != 1; } char chs = src.charAt(svidx); char chp = pat.charAt(pvidx); boolean ans; if (chs == chp || chp == '?') { ans = regexRecursion(src, pat, svidx + 1, pvidx + 1, strg); } else if (chp == '*') { boolean blank = regexRecursion(src, pat, svidx, pvidx + 1, strg); boolean multiple = regexRecursion(src, pat, svidx + 1, pvidx, strg); ans = blank || multiple; } else { ans = false; } strg[svidx][pvidx] = ans ? 2 : 1; return ans; } /** * Method 4: Determines if the given source string matches the given pattern using bottom-up dynamic programming (tabulation). * This method builds a solution iteratively by filling out a table, where each cell represents whether a substring * of the source string matches a substring of the pattern. * * Time Complexity: O(N * M), where N is the length of the source string and M is the length of the pattern. * Space Complexity: O(N * M) for the table used in the tabulation process. * * @param src The source string to be matched against the pattern. * @param pat The pattern containing wildcards ('*' matches a sequence of characters, '?' matches a single character). * @return {@code true} if the source string matches the pattern, {@code false} otherwise. */ static boolean regexBU(String src, String pat) { boolean[][] strg = new boolean[src.length() + 1][pat.length() + 1]; strg[src.length()][pat.length()] = true; for (int row = src.length(); row >= 0; row--) { for (int col = pat.length() - 1; col >= 0; col--) { if (row == src.length()) { if (pat.charAt(col) == '*') { strg[row][col] = strg[row][col + 1]; } else { strg[row][col] = false; } } else { char chs = src.charAt(row); char chp = pat.charAt(col); boolean ans; if (chs == chp || chp == '?') { ans = strg[row + 1][col + 1]; } else if (chp == '*') { boolean blank = strg[row][col + 1]; boolean multiple = strg[row + 1][col]; ans = blank || multiple; } else { ans = false; } strg[row][col] = ans; } } } return strg[0][0]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java
src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java
package com.thealgorithms.dynamicprogramming; /** * Tabulation (Bottom-Up) Solution for 0-1 Knapsack Problem. * This method uses dynamic programming to build up a solution iteratively, * filling a 2-D array where each entry dp[i][w] represents the maximum value * achievable with the first i items and a knapsack capacity of w. * * The tabulation approach is efficient because it avoids redundant calculations * by solving all subproblems in advance and storing their results, ensuring * each subproblem is solved only once. This is a key technique in dynamic programming, * making it possible to solve problems that would otherwise be infeasible due to * exponential time complexity in naive recursive solutions. * * Time Complexity: O(n * W), where n is the number of items and W is the knapsack capacity. * Space Complexity: O(n * W) for the DP table. * * For more information, see: * https://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming */ public final class KnapsackZeroOneTabulation { private KnapsackZeroOneTabulation() { // Prevent instantiation } /** * Solves the 0-1 Knapsack problem using the bottom-up tabulation technique. * @param values the values of the items * @param weights the weights of the items * @param capacity the total capacity of the knapsack * @param itemCount the number of items * @return the maximum value that can be put in the knapsack * @throws IllegalArgumentException if input arrays are null, of different lengths,or if capacity or itemCount is invalid */ public static int compute(final int[] values, final int[] weights, final int capacity, final int itemCount) { if (values == null || weights == null) { throw new IllegalArgumentException("Values and weights arrays must not be null."); } if (values.length != weights.length) { throw new IllegalArgumentException("Values and weights arrays must be non-null and of same length."); } if (capacity < 0) { throw new IllegalArgumentException("Capacity must not be negative."); } if (itemCount < 0 || itemCount > values.length) { throw new IllegalArgumentException("Item count must be between 0 and the length of the values array."); } final int[][] dp = new int[itemCount + 1][capacity + 1]; for (int i = 1; i <= itemCount; i++) { final int currentValue = values[i - 1]; final int currentWeight = weights[i - 1]; for (int w = 1; w <= capacity; w++) { if (currentWeight <= w) { final int includeItem = currentValue + dp[i - 1][w - currentWeight]; final int excludeItem = dp[i - 1][w]; dp[i][w] = Math.max(includeItem, excludeItem); } else { dp[i][w] = dp[i - 1][w]; } } } return dp[itemCount][capacity]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java
package com.thealgorithms.dynamicprogramming; /** * Implementation of the Longest Increasing Subsequence (LIS) problem using * an O(n log n) dynamic programming solution enhanced with binary search. * * @author Vusal Huseynov (https://github.com/huseynovvusal) */ public final class LongestIncreasingSubsequenceNLogN { private LongestIncreasingSubsequenceNLogN() { } /** * Finds the index of the smallest element in the array that is greater than * or equal to the target using binary search. The search is restricted to * the first `size` elements of the array. * * @param arr The array to search in (assumed to be sorted up to `size`). * @param size The number of valid elements in the array. * @param target The target value to find the lower bound for. * @return The index of the lower bound. */ private static int lowerBound(int[] arr, int target, int size) { int l = 0; int r = size; while (l < r) { int mid = l + (r - l) / 2; if (target > arr[mid]) { // Move right if target is greater than mid element l = mid + 1; } else { // Move left if target is less than or equal to mid element r = mid; } } // Return the index where the target can be inserted return l; } /** * Calculates the length of the Longest Increasing Subsequence (LIS) in the given array. * * @param arr The input array of integers. * @return The length of the LIS. */ public static int lengthOfLIS(int[] arr) { if (arr == null || arr.length == 0) { return 0; // Return 0 for empty or null arrays } // tails[i] - the smallest end element of an increasing subsequence of length i+1 int[] tails = new int[arr.length]; // size - the length of the longest increasing subsequence found so far int size = 0; for (int x : arr) { // Find the position to replace or extend the subsequence int index = lowerBound(tails, x, size); // Update the tails array with the current element tails[index] = x; // If the element extends the subsequence, increase the size if (index == size) { size++; } } // Return the length of the LIS return size; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java
src/main/java/com/thealgorithms/dynamicprogramming/RodCutting.java
package com.thealgorithms.dynamicprogramming; /** * A Dynamic Programming solution for the Rod cutting problem. * Returns the best obtainable price for a rod of length n and price[] as prices of different pieces. */ public final class RodCutting { private RodCutting() { } /** * This method calculates the maximum obtainable value for cutting a rod of length n * into different pieces, given the prices for each possible piece length. * * @param price An array representing the prices of different pieces, where price[i-1] * represents the price of a piece of length i. * @param n The length of the rod to be cut. * @throws IllegalArgumentException if the price array is null or empty, or if n is less than 0. * @return The maximum obtainable value. */ public static int cutRod(int[] price, int n) { if (price == null || price.length == 0) { throw new IllegalArgumentException("Price array cannot be null or empty."); } if (n < 0) { throw new IllegalArgumentException("Rod length cannot be negative."); } // Create an array to store the maximum obtainable values for each rod length. int[] val = new int[n + 1]; val[0] = 0; // Calculate the maximum value for each rod length from 1 to n. for (int i = 1; i <= n; i++) { int maxVal = Integer.MIN_VALUE; // Try all possible ways to cut the rod and find the maximum value. for (int j = 1; j <= i; j++) { maxVal = Math.max(maxVal, price[j - 1] + val[i - j]); } // Store the maximum value for the current rod length. val[i] = maxVal; } // The final element of 'val' contains the maximum obtainable value for a rod of length 'n'. return val[n]; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
package com.thealgorithms.dynamicprogramming; /** * This class implements the Longest Common Subsequence (LCS) problem. * The LCS of two sequences is the longest sequence that appears in both * sequences * in the same order, but not necessarily consecutively. * * This implementation uses dynamic programming to find the LCS of two strings. */ final class LongestCommonSubsequence { private LongestCommonSubsequence() { } /** * Returns the Longest Common Subsequence (LCS) of two given strings. * * @param str1 The first string. * @param str2 The second string. * @return The LCS of the two strings, or null if one of the strings is null. */ public static String getLCS(String str1, String str2) { // If either string is null, return null as LCS can't be computed. if (str1 == null || str2 == null) { return null; } // If either string is empty, return an empty string as LCS. if (str1.length() == 0 || str2.length() == 0) { return ""; } // Convert the strings into arrays of characters String[] arr1 = str1.split(""); String[] arr2 = str2.split(""); // lcsMatrix[i][j] = LCS(first i characters of str1, first j characters of str2) int[][] lcsMatrix = new int[arr1.length + 1][arr2.length + 1]; // Base Case: Fill the LCS matrix 0th row & 0th column with 0s // as LCS of any string with an empty string is 0. for (int i = 0; i < arr1.length + 1; i++) { lcsMatrix[i][0] = 0; } for (int j = 1; j < arr2.length + 1; j++) { lcsMatrix[0][j] = 0; } // Build the LCS matrix by comparing characters of str1 & str2 for (int i = 1; i < arr1.length + 1; i++) { for (int j = 1; j < arr2.length + 1; j++) { // If characters match, the LCS increases by 1 if (arr1[i - 1].equals(arr2[j - 1])) { lcsMatrix[i][j] = lcsMatrix[i - 1][j - 1] + 1; } else { // Otherwise, take the maximum of the left or above values lcsMatrix[i][j] = Math.max(lcsMatrix[i - 1][j], lcsMatrix[i][j - 1]); } } } // Call helper function to reconstruct the LCS from the matrix return lcsString(str1, str2, lcsMatrix); } /** * Reconstructs the LCS string from the LCS matrix. * * @param str1 The first string. * @param str2 The second string. * @param lcsMatrix The matrix storing the lengths of LCSs * of substrings of str1 and str2. * @return The LCS string. */ public static String lcsString(String str1, String str2, int[][] lcsMatrix) { StringBuilder lcs = new StringBuilder(); // Hold the LCS characters. int i = str1.length(); // Start from the end of str1. int j = str2.length(); // Start from the end of str2. // Trace back through the LCS matrix to reconstruct the LCS while (i > 0 && j > 0) { // If characters match, add to the LCS and move diagonally in the matrix if (str1.charAt(i - 1) == str2.charAt(j - 1)) { lcs.append(str1.charAt(i - 1)); i--; j--; } else if (lcsMatrix[i - 1][j] > lcsMatrix[i][j - 1]) { // If the value above is larger, move up i--; } else { // If the value to the left is larger, move left j--; } } return lcs.reverse().toString(); // LCS built in reverse, so reverse it back } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java
src/main/java/com/thealgorithms/maths/CircularConvolutionFFT.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collection; /** * Class for circular convolution of two discrete signals using the convolution * theorem. * * @author Ioannis Karavitsis * @version 1.0 */ public final class CircularConvolutionFFT { private CircularConvolutionFFT() { } /** * This method pads the signal with zeros until it reaches the new size. * * @param x The signal to be padded. * @param newSize The new size of the signal. */ private static void padding(Collection<FFT.Complex> x, int newSize) { if (x.size() < newSize) { int diff = newSize - x.size(); for (int i = 0; i < diff; i++) { x.add(new FFT.Complex()); } } } /** * Discrete circular convolution function. It uses the convolution theorem * for discrete signals: convolved = IDFT(DFT(a)*DFT(b)). Then we use the * FFT algorithm for faster calculations of the two DFTs and the final IDFT. * * <p> * More info: https://en.wikipedia.org/wiki/Convolution_theorem * * @param a The first signal. * @param b The other signal. * @return The convolved signal. */ public static ArrayList<FFT.Complex> fftCircularConvolution(ArrayList<FFT.Complex> a, ArrayList<FFT.Complex> b) { int convolvedSize = Math.max(a.size(), b.size()); // The two signals must have the same size equal to the bigger one padding(a, convolvedSize); // Zero padding the smaller signal padding(b, convolvedSize); /* Find the FFTs of both signal. Here we use the Bluestein algorithm because we want the FFT * to have the same length with the signal and not bigger */ FFTBluestein.fftBluestein(a, false); FFTBluestein.fftBluestein(b, false); ArrayList<FFT.Complex> convolved = new ArrayList<>(); for (int i = 0; i < a.size(); i++) { convolved.add(a.get(i).multiply(b.get(i))); // FFT(a)*FFT(b) } FFTBluestein.fftBluestein(convolved, true); // IFFT return convolved; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/VampireNumber.java
src/main/java/com/thealgorithms/maths/VampireNumber.java
package com.thealgorithms.maths; import java.util.ArrayList; /** * In number theory, a vampire number (or true vampire number) is a composite * natural number with an even number of digits, that can be factored into two * natural numbers each with half as many digits as the original number and not * both with trailing zeroes, where the two factors contain precisely all the * digits of the original number, in any order, counting multiplicity. The first * vampire number is 1260 = 21 × 60. * * @see <a href='https://en.wikipedia.org/wiki/Vampire_number'>Vampire number on Wikipedia</a> */ public final class VampireNumber { // Forbid instantiation. private VampireNumber() { } static boolean isVampireNumber(int a, int b, boolean ignorePseudoVampireNumbers) { // Pseudo vampire numbers don't have to be of n/2 digits. E.g., 126 = 6 x 21 is such a number. if (ignorePseudoVampireNumbers && String.valueOf(a).length() != String.valueOf(b).length()) { return false; } String mulDigits = splitIntoSortedDigits(a * b); String factorDigits = splitIntoSortedDigits(a, b); return mulDigits.equals(factorDigits); } // Method to split a pair of numbers to digits and sort them in the ascending order. static String splitIntoSortedDigits(int... nums) { // Collect all digits in a list. ArrayList<Integer> digits = new ArrayList<>(); for (int num : nums) { while (num > 0) { digits.add(num % 10); num /= 10; } } // Sort all digits and convert to String. StringBuilder res = new StringBuilder(); digits.stream().sorted().forEach(res::append); return res.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java
src/main/java/com/thealgorithms/maths/SumOfArithmeticSeries.java
package com.thealgorithms.maths; /** * In mathematics, an arithmetic progression (AP) or arithmetic sequence is a * sequence of numbers such that the difference between the consecutive terms is * constant. Difference here means the second minus the first. For instance, the * sequence 5, 7, 9, 11, 13, 15, . . . is an arithmetic progression with common * difference of 2. * * <p> * Wikipedia: https://en.wikipedia.org/wiki/Arithmetic_progression */ public final class SumOfArithmeticSeries { private SumOfArithmeticSeries() { } /** * Calculate sum of arithmetic series * * @param firstTerm the initial term of an arithmetic series * @param commonDiff the common difference of an arithmetic series * @param numOfTerms the total terms of an arithmetic series * @return sum of given arithmetic series */ public static double sumOfSeries(final double firstTerm, final double commonDiff, final int numOfTerms) { if (numOfTerms < 0) { throw new IllegalArgumentException("numOfTerms nonnegative."); } return (numOfTerms / 2.0 * (2 * firstTerm + (numOfTerms - 1) * commonDiff)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FindKthNumber.java
src/main/java/com/thealgorithms/maths/FindKthNumber.java
package com.thealgorithms.maths; import java.util.Collections; import java.util.PriorityQueue; import java.util.Random; /** * Use a quicksort-based approach to identify the k-th largest or k-th max element within the provided array. */ public final class FindKthNumber { private FindKthNumber() { } private static final Random RANDOM = new Random(); public static int findKthMax(int[] array, int k) { if (k <= 0 || k > array.length) { throw new IllegalArgumentException("k must be between 1 and the size of the array"); } // Convert k-th largest to index for QuickSelect return quickSelect(array, 0, array.length - 1, array.length - k); } private static int quickSelect(int[] array, int left, int right, int kSmallest) { if (left == right) { return array[left]; } // Randomly select a pivot index int pivotIndex = left + RANDOM.nextInt(right - left + 1); pivotIndex = partition(array, left, right, pivotIndex); if (kSmallest == pivotIndex) { return array[kSmallest]; } else if (kSmallest < pivotIndex) { return quickSelect(array, left, pivotIndex - 1, kSmallest); } else { return quickSelect(array, pivotIndex + 1, right, kSmallest); } } private static int partition(int[] array, int left, int right, int pivotIndex) { int pivotValue = array[pivotIndex]; // Move pivot to end swap(array, pivotIndex, right); int storeIndex = left; // Move all smaller elements to the left for (int i = left; i < right; i++) { if (array[i] < pivotValue) { swap(array, storeIndex, i); storeIndex++; } } // Move pivot to its final place swap(array, storeIndex, right); return storeIndex; } private static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } public static int findKthMaxUsingHeap(int[] array, int k) { if (k <= 0 || k > array.length) { throw new IllegalArgumentException("k must be between 1 and the size of the array"); } PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // using max-heap to store numbers. for (int num : array) { maxHeap.add(num); } while (k > 1) { maxHeap.poll(); // removing max number from heap k--; } return maxHeap.peek(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Area.java
src/main/java/com/thealgorithms/maths/Area.java
package com.thealgorithms.maths; /** * Find the area of various geometric shapes */ public final class Area { private Area() { } /** * String of IllegalArgumentException for radius */ private static final String POSITIVE_RADIUS = "Must be a positive radius"; /** * String of IllegalArgumentException for height */ private static final String POSITIVE_HEIGHT = "Must be a positive height"; /** * String of IllegalArgumentException for base */ private static final String POSITIVE_BASE = "Must be a positive base"; /** * Calculate the surface area of a cube. * * @param sideLength side length of cube * @return surface area of given cube */ public static double surfaceAreaCube(final double sideLength) { if (sideLength <= 0) { throw new IllegalArgumentException("Must be a positive sideLength"); } return 6 * sideLength * sideLength; } /** * Calculate the surface area of a sphere. * * @param radius radius of sphere * @return surface area of given sphere */ public static double surfaceAreaSphere(final double radius) { if (radius <= 0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } return 4 * Math.PI * radius * radius; } /** * Calculate the surface area of a pyramid with a square base. * * @param sideLength side length of the square base * @param slantHeight slant height of the pyramid * @return surface area of the given pyramid */ public static double surfaceAreaPyramid(final double sideLength, final double slantHeight) { if (sideLength <= 0) { throw new IllegalArgumentException("Must be a positive sideLength"); } if (slantHeight <= 0) { throw new IllegalArgumentException("Must be a positive slantHeight"); } double baseArea = sideLength * sideLength; double lateralSurfaceArea = 2 * sideLength * slantHeight; return baseArea + lateralSurfaceArea; } /** * Calculate the area of a rectangle. * * @param length length of a rectangle * @param width width of a rectangle * @return area of given rectangle */ public static double surfaceAreaRectangle(final double length, final double width) { if (length <= 0) { throw new IllegalArgumentException("Must be a positive length"); } if (width <= 0) { throw new IllegalArgumentException("Must be a positive width"); } return length * width; } /** * Calculate surface area of a cylinder. * * @param radius radius of the floor * @param height height of the cylinder. * @return volume of given cylinder */ public static double surfaceAreaCylinder(final double radius, final double height) { if (radius <= 0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return 2 * (Math.PI * radius * radius + Math.PI * radius * height); } /** * Calculate the area of a square. * * @param sideLength side length of square * @return area of given square */ public static double surfaceAreaSquare(final double sideLength) { if (sideLength <= 0) { throw new IllegalArgumentException("Must be a positive sideLength"); } return sideLength * sideLength; } /** * Calculate the area of a triangle. * * @param base base of triangle * @param height height of triangle * @return area of given triangle */ public static double surfaceAreaTriangle(final double base, final double height) { if (base <= 0) { throw new IllegalArgumentException(POSITIVE_BASE); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return base * height / 2; } /** * Calculate the area of a parallelogram. * * @param base base of a parallelogram * @param height height of a parallelogram * @return area of given parallelogram */ public static double surfaceAreaParallelogram(final double base, final double height) { if (base <= 0) { throw new IllegalArgumentException(POSITIVE_BASE); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return base * height; } /** * Calculate the area of a trapezium. * * @param base1 upper base of trapezium * @param base2 bottom base of trapezium * @param height height of trapezium * @return area of given trapezium */ public static double surfaceAreaTrapezium(final double base1, final double base2, final double height) { if (base1 <= 0) { throw new IllegalArgumentException(POSITIVE_BASE + 1); } if (base2 <= 0) { throw new IllegalArgumentException(POSITIVE_BASE + 2); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return (base1 + base2) * height / 2; } /** * Calculate the area of a circle. * * @param radius radius of circle * @return area of given circle */ public static double surfaceAreaCircle(final double radius) { if (radius <= 0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } return Math.PI * radius * radius; } /** * Calculate the surface area of a hemisphere. * * @param radius radius of hemisphere * @return surface area of given hemisphere */ public static double surfaceAreaHemisphere(final double radius) { if (radius <= 0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } return 3 * Math.PI * radius * radius; } /** * Calculate the surface area of a cone. * * @param radius radius of cone. * @param height of cone. * @return surface area of given cone. */ public static double surfaceAreaCone(final double radius, final double height) { if (radius <= 0) { throw new IllegalArgumentException(POSITIVE_RADIUS); } if (height <= 0) { throw new IllegalArgumentException(POSITIVE_HEIGHT); } return Math.PI * radius * (radius + Math.pow(height * height + radius * radius, 0.5)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AbsoluteValue.java
src/main/java/com/thealgorithms/maths/AbsoluteValue.java
package com.thealgorithms.maths; public final class AbsoluteValue { private AbsoluteValue() { } /** * Returns the absolute value of a number. * * @param number The number to be transformed * @return The absolute value of the {@code number} */ public static int getAbsValue(int number) { return number < 0 ? -number : number; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ADTFraction.java
src/main/java/com/thealgorithms/maths/ADTFraction.java
package com.thealgorithms.maths; public record ADTFraction(int numerator, int denominator) { /** * Initializes a newly created {@code ADTFraction} object so that it represents * a fraction with the {@code numerator} and {@code denominator} provided as arguments. * * @param numerator The fraction numerator * @param denominator The fraction denominator */ public ADTFraction { if (denominator == 0) { throw new IllegalArgumentException("Denominator cannot be 0"); } } /** * Add two fractions. * * @param fraction the {@code ADTFraction} to add * @return A new {@code ADTFraction} containing the result of the operation */ public ADTFraction plus(ADTFraction fraction) { var numerator = this.denominator * fraction.numerator + this.numerator * fraction.denominator; var denominator = this.denominator * fraction.denominator; return new ADTFraction(numerator, denominator); } /** * Multiply fraction by a number. * * @param number the number to multiply * @return A new {@code ADTFraction} containing the result of the operation */ public ADTFraction times(int number) { return times(new ADTFraction(number, 1)); } /** * Multiply two fractions. * * @param fraction the {@code ADTFraction} to multiply * @return A new {@code ADTFraction} containing the result of the operation */ public ADTFraction times(ADTFraction fraction) { var numerator = this.numerator * fraction.numerator; var denominator = this.denominator * fraction.denominator; return new ADTFraction(numerator, denominator); } /** * Generates the reciprocal of the fraction. * * @return A new {@code ADTFraction} with the {@code numerator} and {@code denominator} switched */ public ADTFraction reciprocal() { return new ADTFraction(this.denominator, this.numerator); } /** * Calculates the result of the fraction. * * @return The numerical result of the division between {@code numerator} and {@code * denominator} */ public float value() { return (float) this.numerator / this.denominator; } /** * Returns a string representation of this {@code ADTFraction} in the format * {@code numerator}/{@code denominator}. * * @return A string representation of this {@code ADTFraction} */ @Override public String toString() { return String.format("%d/%d", this.numerator, this.denominator); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java
src/main/java/com/thealgorithms/maths/SumWithoutArithmeticOperators.java
package com.thealgorithms.maths; public class SumWithoutArithmeticOperators { /** * Calculate the sum of two numbers a and b without using any arithmetic operators (+, -, *, /). * All the integers associated are unsigned 32-bit integers *https://stackoverflow.com/questions/365522/what-is-the-best-way-to-add-two-numbers-without-using-the-operator *@param a - It is the first number *@param b - It is the second number *@return returns an integer which is the sum of the first and second number */ public int getSum(int a, int b) { if (b == 0) { return a; } int sum = a ^ b; int carry = (a & b) << 1; return getSum(sum, carry); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/NumberPersistence.java
src/main/java/com/thealgorithms/maths/NumberPersistence.java
package com.thealgorithms.maths; /** * A utility class for calculating the persistence of a number. * * <p>This class provides methods to calculate: * <ul> * <li>Multiplicative persistence: The number of steps required to reduce a number to a single digit by multiplying its digits.</li> * <li>Additive persistence: The number of steps required to reduce a number to a single digit by summing its digits.</li> * </ul> * * <p>This class is final and cannot be instantiated. * * @see <a href="https://en.wikipedia.org/wiki/Persistence_of_a_number">Wikipedia: Persistence of a number</a> */ public final class NumberPersistence { // Private constructor to prevent instantiation private NumberPersistence() { } /** * Calculates the multiplicative persistence of a given number. * * <p>Multiplicative persistence is the number of steps required to reduce a number to a single digit * by multiplying its digits repeatedly. * * @param num the number to calculate persistence for; must be non-negative * @return the multiplicative persistence of the number * @throws IllegalArgumentException if the input number is negative */ public static int multiplicativePersistence(int num) { if (num < 0) { throw new IllegalArgumentException("multiplicativePersistence() does not accept negative values"); } int steps = 0; while (num >= 10) { int product = 1; int temp = num; while (temp > 0) { product *= temp % 10; temp /= 10; } num = product; steps++; } return steps; } /** * Calculates the additive persistence of a given number. * * <p>Additive persistence is the number of steps required to reduce a number to a single digit * by summing its digits repeatedly. * * @param num the number to calculate persistence for; must be non-negative * @return the additive persistence of the number * @throws IllegalArgumentException if the input number is negative */ public static int additivePersistence(int num) { if (num < 0) { throw new IllegalArgumentException("additivePersistence() does not accept negative values"); } int steps = 0; while (num >= 10) { int sum = 0; int temp = num; while (temp > 0) { sum += temp % 10; temp /= 10; } num = sum; steps++; } return steps; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/EulersFunction.java
src/main/java/com/thealgorithms/maths/EulersFunction.java
package com.thealgorithms.maths; /** * Utility class for computing * <a href="https://en.wikipedia.org/wiki/Euler%27s_totient_function">Euler's totient function</a>. */ public final class EulersFunction { private EulersFunction() { } /** * Validates that the input is a positive integer. * * @param n the input number to validate * @throws IllegalArgumentException if {@code n} is non-positive */ private static void checkInput(int n) { if (n <= 0) { throw new IllegalArgumentException("n must be positive."); } } /** * Computes the value of Euler's totient function for a given input. * This function has a time complexity of O(sqrt(n)). * * @param n the input number * @return the value of Euler's totient function for the given input * @throws IllegalArgumentException if {@code n} is non-positive */ public static int getEuler(int n) { checkInput(n); int result = n; for (int i = 2; i * i <= n; i++) { if (n % i == 0) { while (n % i == 0) { n /= i; } result -= result / i; } } if (n > 1) { result -= result / n; } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Factorial.java
src/main/java/com/thealgorithms/maths/Factorial.java
package com.thealgorithms.maths; public final class Factorial { private Factorial() { } /** * Calculate factorial N using iteration * * @param n the number * @return the factorial of {@code n} */ public static long factorial(int n) { if (n < 0) { throw new IllegalArgumentException("Input number cannot be negative"); } long factorial = 1; for (int i = 1; i <= n; ++i) { factorial *= i; } return factorial; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FastExponentiation.java
src/main/java/com/thealgorithms/maths/FastExponentiation.java
package com.thealgorithms.maths; /** * This class provides a method to perform fast exponentiation (exponentiation by squaring), * which calculates (base^exp) % mod efficiently. * * <p>The algorithm works by repeatedly squaring the base and reducing the exponent * by half at each step. It exploits the fact that: * <ul> * <li>If exp is even, (base^exp) = (base^(exp/2))^2</li> * <li>If exp is odd, (base^exp) = base * (base^(exp-1))</li> * </ul> * The result is computed modulo `mod` at each step to avoid overflow and keep the result within bounds. * </p> * * <p><strong>Time complexity:</strong> O(log(exp)) — much faster than naive exponentiation (O(exp)).</p> * * For more information, please visit {@link https://en.wikipedia.org/wiki/Exponentiation_by_squaring} */ public final class FastExponentiation { /** * Private constructor to hide the implicit public one. */ private FastExponentiation() { } /** * Performs fast exponentiation to calculate (base^exp) % mod using the method * of exponentiation by squaring. * * <p>This method efficiently computes the result by squaring the base and halving * the exponent at each step. It multiplies the base to the result when the exponent is odd. * * @param base the base number to be raised to the power of exp * @param exp the exponent to which the base is raised * @param mod the modulus to ensure the result does not overflow * @return (base^exp) % mod * @throws IllegalArgumentException if the modulus is less than or equal to 0 * @throws ArithmeticException if the exponent is negative (not supported in this implementation) */ public static long fastExponentiation(long base, long exp, long mod) { if (mod <= 0) { throw new IllegalArgumentException("Modulus must be positive."); } if (exp < 0) { throw new ArithmeticException("Negative exponent is not supported."); } long result = 1; base = base % mod; // Take the modulus of the base to handle large base values // Fast exponentiation by squaring algorithm while (exp > 0) { // If exp is odd, multiply the base to the result if ((exp & 1) == 1) { // exp & 1 checks if exp is odd result = result * base % mod; } // Square the base and halve the exponent base = base * base % mod; // base^2 % mod to avoid overflow exp >>= 1; // Right shift exp to divide it by 2 } return result; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java
src/main/java/com/thealgorithms/maths/SquareRootWithNewtonRaphsonMethod.java
package com.thealgorithms.maths; /* *To learn about the method, visit the link below : * https://en.wikipedia.org/wiki/Newton%27s_method * * To obtain the square root, no built-in functions should be used * * The formula to calculate the root is : root = 0.5(x + n/x), * here, n is the no. whose square root has to be calculated and * x has to be guessed such that, the calculation should result into * the square root of n. * And the root will be obtained when the error < 0.5 or the precision value can also * be changed according to the user preference. */ public final class SquareRootWithNewtonRaphsonMethod { private SquareRootWithNewtonRaphsonMethod() { } public static double squareRoot(int n) { double x = n; // initially taking a guess that x = n. double root = 0.5 * (x + n / x); // applying Newton-Raphson Method. while (Math.abs(root - x) > 0.0000001) { // root - x = error and error < 0.0000001, 0.0000001 // is the precision value taken over here. x = root; // decreasing the value of x to root, i.e. decreasing the guess. root = 0.5 * (x + n / x); } return root; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/PiApproximation.java
src/main/java/com/thealgorithms/maths/PiApproximation.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Implementation to calculate an estimate of the number π (Pi). * * We take a random point P with coordinates (x, y) such that 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. * If x² + y² ≤ 1, then the point is inside the quarter disk of radius 1, * else the point is outside. We know that the probability of the point being * inside the quarter disk is equal to π/4. * * * @author [Yash Rajput](https://github.com/the-yash-rajput) */ public final class PiApproximation { private PiApproximation() { throw new AssertionError("No instances."); } /** * Structure representing a point with coordinates (x, y) * where 0 ≤ x ≤ 1 and 0 ≤ y ≤ 1. */ static class Point { double x; double y; Point(double x, double y) { this.x = x; this.y = y; } } /** * This function uses the points in a given list (drawn at random) * to return an approximation of the number π. * * @param pts List of points where each point contains x and y coordinates * @return An estimate of the number π */ public static double approximatePi(List<Point> pts) { double count = 0; // Points in circle for (Point p : pts) { if ((p.x * p.x) + (p.y * p.y) <= 1) { count++; } } return 4.0 * count / pts.size(); } /** * Generates random points for testing the Pi approximation. * * @param numPoints Number of random points to generate * @return List of random points */ public static List<Point> generateRandomPoints(int numPoints) { List<Point> points = new ArrayList<>(); Random rand = new Random(); for (int i = 0; i < numPoints; i++) { double x = rand.nextDouble(); // Random value between 0 and 1 double y = rand.nextDouble(); // Random value between 0 and 1 points.add(new Point(x, y)); } return points; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/MaxValue.java
src/main/java/com/thealgorithms/maths/MaxValue.java
package com.thealgorithms.maths; public final class MaxValue { private MaxValue() { } /** * Returns the greater of two {@code int} values. That is, the result is the * argument closer to the value of {@link Integer#MAX_VALUE}. If the * arguments have the same value, the result is that same value. * * @param a an argument. * @param b another argument. * @return the larger of {@code a} and {@code b}. */ public static int max(int a, int b) { return a >= b ? a : b; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FibonacciNumberGoldenRation.java
src/main/java/com/thealgorithms/maths/FibonacciNumberGoldenRation.java
package com.thealgorithms.maths; /** * This class provides methods for calculating Fibonacci numbers using Binet's formula. * Binet's formula is based on the golden ratio and allows computing Fibonacci numbers efficiently. * * @see <a href="https://en.wikipedia.org/wiki/Fibonacci_sequence#Binet's_formula">Binet's formula on Wikipedia</a> */ public final class FibonacciNumberGoldenRation { private FibonacciNumberGoldenRation() { // Private constructor to prevent instantiation of this utility class. } /** * Compute the limit for 'n' that fits in a long data type. * Reducing the limit to 70 due to potential floating-point arithmetic errors * that may result in incorrect results for larger inputs. */ public static final int MAX_ARG = 70; /** * Calculates the nth Fibonacci number using Binet's formula. * * @param n The index of the Fibonacci number to calculate. * @return The nth Fibonacci number as a long. * @throws IllegalArgumentException if the input 'n' is negative or exceeds the range of a long data type. */ public static long compute(int n) { if (n < 0) { throw new IllegalArgumentException("Input 'n' must be a non-negative integer."); } if (n > MAX_ARG) { throw new IllegalArgumentException("Input 'n' is too big to give accurate result."); } if (n <= 1) { return n; } // Calculate the nth Fibonacci number using the golden ratio formula final double sqrt5 = Math.sqrt(5); final double phi = (1 + sqrt5) / 2; final double psi = (1 - sqrt5) / 2; final double result = (Math.pow(phi, n) - Math.pow(psi, n)) / sqrt5; // Round to the nearest integer and return as a long return Math.round(result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/LongDivision.java
src/main/java/com/thealgorithms/maths/LongDivision.java
// Given two integers dividend and divisor, divide two integers without using multiplication, // division, and mod operator. // // The integer division should truncate toward zero, which means losing its fractional part. // For example, 8.345 would be truncated to 8, and -2.7335 would be truncated to -2. My // method used Long Division, here is the source // "https://en.wikipedia.org/wiki/Long_division" package com.thealgorithms.maths; public final class LongDivision { private LongDivision() { } public static int divide(int dividend, int divisor) { long newDividend1 = dividend; long newDivisor1 = divisor; if (divisor == 0) { return 0; } if (dividend < 0) { newDividend1 = newDividend1 * -1; } if (divisor < 0) { newDivisor1 = newDivisor1 * -1; } if (dividend == 0 || newDividend1 < newDivisor1) { return 0; } StringBuilder answer = new StringBuilder(); String dividendString = "" + newDividend1; int lastIndex = 0; String remainder = ""; for (int i = 0; i < dividendString.length(); i++) { String partV1 = remainder + "" + dividendString.substring(lastIndex, i + 1); long part1 = Long.parseLong(partV1); if (part1 > newDivisor1) { int quotient = 0; while (part1 >= newDivisor1) { part1 = part1 - newDivisor1; quotient++; } answer.append(quotient); } else if (part1 == newDivisor1) { int quotient = 0; while (part1 >= newDivisor1) { part1 = part1 - newDivisor1; quotient++; } answer.append(quotient); } else if (part1 == 0) { answer.append(0); } else if (part1 < newDivisor1) { answer.append(0); } if (!(part1 == 0)) { remainder = String.valueOf(part1); } else { remainder = ""; } lastIndex++; } if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0)) { try { return Integer.parseInt(answer.toString()) * (-1); } catch (NumberFormatException e) { return -2147483648; } } try { return Integer.parseInt(answer.toString()); } catch (NumberFormatException e) { return 2147483647; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Mode.java
src/main/java/com/thealgorithms/maths/Mode.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Utility class to calculate the mode(s) of an array of integers. * <p> * The mode of an array is the integer value(s) that occur most frequently. * If multiple values have the same highest frequency, all such values are returned. * </p> */ public final class Mode { private Mode() { } /** * Computes the mode(s) of the specified array of integers. * <p> * If the input array is empty, this method returns {@code null}. * If multiple numbers share the highest frequency, all are returned in the result array. * </p> * * @param numbers an array of integers to analyze * @return an array containing the mode(s) of the input array, or {@code null} if the input is empty */ public static int[] mode(final int[] numbers) { if (numbers.length == 0) { return null; } Map<Integer, Integer> count = new HashMap<>(); for (int num : numbers) { count.put(num, count.getOrDefault(num, 0) + 1); } int max = Collections.max(count.values()); List<Integer> modes = new ArrayList<>(); for (final var entry : count.entrySet()) { if (entry.getValue() == max) { modes.add(entry.getKey()); } } return modes.stream().mapToInt(Integer::intValue).toArray(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java
src/main/java/com/thealgorithms/maths/FibonacciNumberCheck.java
package com.thealgorithms.maths; /** * Fibonacci: 0 1 1 2 3 5 8 13 21 ... * This code checks Fibonacci Numbers up to 45th number. * Other checks fail because of 'long'-type overflow. */ public final class FibonacciNumberCheck { private FibonacciNumberCheck() { } /** * Check if a number is perfect square number * * @param number the number to be checked * @return <tt>true</tt> if {@code number} is a perfect square, otherwise * <tt>false</tt> */ public static boolean isPerfectSquare(long number) { long sqrt = (long) Math.sqrt(number); return sqrt * sqrt == number; } /** * Check if a number is a Fibonacci number. This is true if and only if at * least one of 5x^2+4 or 5x^2-4 is a perfect square * * @param number the number * @return <tt>true</tt> if {@code number} is a Fibonacci number, otherwise * <tt>false</tt> * @link https://en.wikipedia.org/wiki/Fibonacci_number#Identification */ public static boolean isFibonacciNumber(long number) { long value1 = 5 * number * number + 4; long value2 = 5 * number * number - 4; return isPerfectSquare(value1) || isPerfectSquare(value2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/ZellersCongruence.java
src/main/java/com/thealgorithms/maths/ZellersCongruence.java
package com.thealgorithms.maths; import java.time.DateTimeException; import java.time.LocalDate; import java.util.Objects; /** * A utility class for calculating the day of the week for a given date using Zeller's Congruence. * * <p>Zeller's Congruence is an algorithm devised by Christian Zeller in the 19th century to calculate * the day of the week for any Julian or Gregorian calendar date. The input date must be in the format * "MM-DD-YYYY" or "MM/DD/YYYY". * * <p>This class is final and cannot be instantiated. * * @see <a href="https://en.wikipedia.org/wiki/Zeller%27s_congruence">Wikipedia: Zeller's Congruence</a> */ public final class ZellersCongruence { private static final String[] DAYS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; // Private constructor to prevent instantiation private ZellersCongruence() { } /** * Calculates the day of the week for a given date using Zeller's Congruence. * * <p>The algorithm works for both Julian and Gregorian calendar dates. The input date must be * in the format "MM-DD-YYYY" or "MM/DD/YYYY". * * @param input the date in the format "MM-DD-YYYY" or "MM/DD/YYYY" * @return a string indicating the day of the week for the given date * @throws IllegalArgumentException if the input format is invalid, the date is invalid, * or the year is out of range */ public static String calculateDay(String input) { if (input == null || input.length() != 10) { throw new IllegalArgumentException("Input date must be 10 characters long in the format MM-DD-YYYY or MM/DD/YYYY."); } int month = parsePart(input.substring(0, 2), 1, 12, "Month must be between 1 and 12."); char sep1 = input.charAt(2); validateSeparator(sep1); int day = parsePart(input.substring(3, 5), 1, 31, "Day must be between 1 and 31."); char sep2 = input.charAt(5); validateSeparator(sep2); int year = parsePart(input.substring(6, 10), 46, 8499, "Year must be between 46 and 8499."); try { Objects.requireNonNull(LocalDate.of(year, month, day)); } catch (DateTimeException e) { throw new IllegalArgumentException("Invalid date.", e); } if (month <= 2) { year -= 1; month += 12; } int century = year / 100; int yearOfCentury = year % 100; int t = (int) (2.6 * month - 5.39); int u = century / 4; int v = yearOfCentury / 4; int f = (int) Math.round((day + yearOfCentury + t + u + v - 2 * century) % 7.0); int correctedDay = (f + 7) % 7; return "The date " + input + " falls on a " + DAYS[correctedDay] + "."; } /** * Parses a part of the date string and validates its range. * * @param part the substring to parse * @param min the minimum valid value * @param max the maximum valid value * @param error the error message to throw if validation fails * @return the parsed integer value * @throws IllegalArgumentException if the part is not a valid number or is out of range */ private static int parsePart(String part, int min, int max, String error) { try { int value = Integer.parseInt(part); if (value < min || value > max) { throw new IllegalArgumentException(error); } return value; } catch (NumberFormatException e) { throw new IllegalArgumentException("Invalid numeric part: " + part, e); } } /** * Validates the separator character in the date string. * * @param sep the separator character * @throws IllegalArgumentException if the separator is not '-' or '/' */ private static void validateSeparator(char sep) { if (sep != '-' && sep != '/') { throw new IllegalArgumentException("Date separator must be '-' or '/'."); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Volume.java
src/main/java/com/thealgorithms/maths/Volume.java
package com.thealgorithms.maths; /* Calculate the volume of various shapes.*/ public final class Volume { private Volume() { } /** * Calculate the volume of a cube. * * @param sideLength length of the given cube's sides * @return volume of the given cube */ public static double volumeCube(double sideLength) { return sideLength * sideLength * sideLength; } /** * Calculate the volume of a cuboid. * * @param width width of given cuboid * @param height height of given cuboid * @param length length of given cuboid * @return volume of given cuboid */ public static double volumeCuboid(double width, double height, double length) { return width * height * length; } /** * Calculate the volume of a sphere. * * @param radius radius of given sphere * @return volume of given sphere */ public static double volumeSphere(double radius) { return (4 * Math.PI * radius * radius * radius) / 3; } /** * Calculate volume of a cylinder * * @param radius radius of the given cylinder's floor * @param height height of the given cylinder * @return volume of given cylinder */ public static double volumeCylinder(double radius, double height) { return Math.PI * radius * radius * height; } /** * Calculate the volume of a hemisphere. * * @param radius radius of given hemisphere * @return volume of given hemisphere */ public static double volumeHemisphere(double radius) { return (2 * Math.PI * radius * radius * radius) / 3; } /** * Calculate the volume of a cone. * * @param radius radius of given cone * @param height of given cone * @return volume of given cone */ public static double volumeCone(double radius, double height) { return (Math.PI * radius * radius * height) / 3; } /** * Calculate the volume of a prism. * * @param baseArea area of the given prism's base * @param height of given prism * @return volume of given prism */ public static double volumePrism(double baseArea, double height) { return baseArea * height; } /** * Calculate the volume of a pyramid. * * @param baseArea of the given pyramid's base * @param height of given pyramid * @return volume of given pyramid */ public static double volumePyramid(double baseArea, double height) { return (baseArea * height) / 3; } /** * Calculate the volume of a frustum of a cone. * * @param r1 radius of the top of the frustum * @param r2 radius of the bottom of the frustum * @param height height of the frustum * @return volume of the frustum */ public static double volumeFrustumOfCone(double r1, double r2, double height) { return (Math.PI * height / 3) * (r1 * r1 + r2 * r2 + r1 * r2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AutoCorrelation.java
src/main/java/com/thealgorithms/maths/AutoCorrelation.java
package com.thealgorithms.maths; /** * Class for linear auto-correlation of a discrete signal * * @author Athina-Frederiki Swinkels * @version 2.0 */ public final class AutoCorrelation { private AutoCorrelation() { } /** * Discrete linear auto-correlation function. * Input and output signals have starting index 0. * * @param x The discrete signal * @return The result of the auto-correlation of signals x. The result is also a signal. */ public static double[] autoCorrelation(double[] x) { /* To find the auto-correlation of a discrete signal x, we perform cross-correlation between x signal and itself. Here's an example: x=[1,2,1,1] y=[1,2,1,1] i=0: [1,2,1,1] [1,2,1,1] result[0]=1*1=1 i=1: [1,2,1,1] [1,2,1,1] result[1]=1*1+2*1=3 i=2: [1,2,1,1] [1,2,1,1] result[2]=1*2+2*1+1*1=5 i=3: [1,2,1,1] [1,2,1,1] result[3]=1*1+2*2+1*1+1*1=7 i=4: [1,2,1,1] [1,2,1,1] result[4]=2*1+1*2+1*1=5 i=5: [1,2,1,1] [1,2,1,1] result[5]=1*1+1*2=3 i=1: [1,2,1,1] [1,2,1,1] result[6]=1*1=1 result=[1,3,5,7,5,3,1] */ return CrossCorrelation.crossCorrelation(x, x); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/AbsoluteMin.java
src/main/java/com/thealgorithms/maths/AbsoluteMin.java
package com.thealgorithms.maths; import java.util.Arrays; public final class AbsoluteMin { private AbsoluteMin() { } /** * Compares the numbers given as arguments to get the absolute min value. * * @param numbers The numbers to compare * @return The absolute min value */ public static int getMinValue(int... numbers) { if (numbers.length == 0) { throw new IllegalArgumentException("Numbers array cannot be empty"); } var absMinWrapper = new Object() { int value = numbers[0]; }; Arrays.stream(numbers).skip(1).filter(number -> Math.abs(number) <= Math.abs(absMinWrapper.value)).forEach(number -> absMinWrapper.value = Math.min(absMinWrapper.value, number)); return absMinWrapper.value; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/Means.java
src/main/java/com/thealgorithms/maths/Means.java
package com.thealgorithms.maths; import java.util.stream.StreamSupport; import org.apache.commons.collections4.IterableUtils; /** * Utility class for computing various types of statistical means. * <p> * This class provides static methods to calculate different types of means * (averages) * from a collection of numbers. All methods accept any {@link Iterable} * collection of * {@link Double} values and return the computed mean as a {@link Double}. * </p> * * <p> * Supported means: * <ul> * <li><b>Arithmetic Mean</b>: The sum of all values divided by the count</li> * <li><b>Geometric Mean</b>: The nth root of the product of n values</li> * <li><b>Harmonic Mean</b>: The reciprocal of the arithmetic mean of * reciprocals</li> * </ul> * </p> * * @see <a href="https://en.wikipedia.org/wiki/Mean">Mean (Wikipedia)</a> * @author Punit Patel */ public final class Means { private Means() { } /** * Computes the arithmetic mean (average) of the given numbers. * <p> * The arithmetic mean is calculated as: (x₁ + x₂ + ... + xₙ) / n * </p> * <p> * Example: For numbers [2, 4, 6], the arithmetic mean is (2+4+6)/3 = 4.0 * </p> * * @param numbers the input numbers (must not be empty) * @return the arithmetic mean of the input numbers * @throws IllegalArgumentException if the input is empty * @see <a href="https://en.wikipedia.org/wiki/Arithmetic_mean">Arithmetic * Mean</a> */ public static Double arithmetic(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); double sum = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + y); int size = IterableUtils.size(numbers); return sum / size; } /** * Computes the geometric mean of the given numbers. * <p> * The geometric mean is calculated as: ⁿ√(x₁ × x₂ × ... × xₙ) * </p> * <p> * Example: For numbers [2, 8], the geometric mean is √(2×8) = √16 = 4.0 * </p> * <p> * Note: This method may produce unexpected results for negative numbers, * as it computes the real-valued nth root which may not exist for negative * products. * </p> * * @param numbers the input numbers (must not be empty) * @return the geometric mean of the input numbers * @throws IllegalArgumentException if the input is empty * @see <a href="https://en.wikipedia.org/wiki/Geometric_mean">Geometric * Mean</a> */ public static Double geometric(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); double product = StreamSupport.stream(numbers.spliterator(), false).reduce(1d, (x, y) -> x * y); int size = IterableUtils.size(numbers); return Math.pow(product, 1.0 / size); } /** * Computes the harmonic mean of the given numbers. * <p> * The harmonic mean is calculated as: n / (1/x₁ + 1/x₂ + ... + 1/xₙ) * </p> * <p> * Example: For numbers [1, 2, 4], the harmonic mean is 3/(1/1 + 1/2 + 1/4) = * 3/1.75 ≈ 1.714 * </p> * <p> * Note: This method will produce unexpected results if any input number is * zero, * as it involves computing reciprocals. * </p> * * @param numbers the input numbers (must not be empty) * @return the harmonic mean of the input numbers * @throws IllegalArgumentException if the input is empty * @see <a href="https://en.wikipedia.org/wiki/Harmonic_mean">Harmonic Mean</a> */ public static Double harmonic(final Iterable<Double> numbers) { checkIfNotEmpty(numbers); double sumOfReciprocals = StreamSupport.stream(numbers.spliterator(), false).reduce(0d, (x, y) -> x + 1d / y); int size = IterableUtils.size(numbers); return size / sumOfReciprocals; } /** * Validates that the input iterable is not empty. * * @param numbers the input numbers to validate * @throws IllegalArgumentException if the input is empty */ private static void checkIfNotEmpty(final Iterable<Double> numbers) { if (!numbers.iterator().hasNext()) { throw new IllegalArgumentException("Empty list given for Mean computation."); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FibonacciLoop.java
src/main/java/com/thealgorithms/maths/FibonacciLoop.java
package com.thealgorithms.maths; import java.math.BigInteger; /** * This class provides methods for calculating Fibonacci numbers using BigInteger for large values of 'n'. */ public final class FibonacciLoop { private FibonacciLoop() { // Private constructor to prevent instantiation of this utility class. } /** * Calculates the nth Fibonacci number. * * @param n The index of the Fibonacci number to calculate. * @return The nth Fibonacci number as a BigInteger. * @throws IllegalArgumentException if the input 'n' is a negative integer. */ public static BigInteger compute(final int n) { if (n < 0) { throw new IllegalArgumentException("Input 'n' must be a non-negative integer."); } if (n <= 1) { return BigInteger.valueOf(n); } BigInteger prev = BigInteger.ZERO; BigInteger current = BigInteger.ONE; for (int i = 2; i <= n; i++) { BigInteger next = prev.add(current); prev = current; current = next; } return current; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/FFTBluestein.java
src/main/java/com/thealgorithms/maths/FFTBluestein.java
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.List; /** * Class for calculating the Fast Fourier Transform (FFT) of a discrete signal * using the Bluestein's algorithm. * * @author Ioannis Karavitsis * @version 1.0 */ public final class FFTBluestein { private FFTBluestein() { } /** * Bluestein's FFT Algorithm. * * <p> * More info: * https://en.wikipedia.org/wiki/Chirp_Z-transform#Bluestein.27s_algorithm * http://tka4.org/materials/lib/Articles-Books/Numerical%20Algorithms/Hartley_Trasform/Bluestein%27s%20FFT%20algorithm%20-%20Wikipedia,%20the%20free%20encyclopedia.htm * * @param x The discrete signal which is then converted to the FFT or the * IFFT of signal x. * @param inverse True if you want to find the inverse FFT. */ public static void fftBluestein(List<FFT.Complex> x, boolean inverse) { int n = x.size(); int bnSize = 2 * n - 1; int direction = inverse ? -1 : 1; ArrayList<FFT.Complex> an = new ArrayList<>(); ArrayList<FFT.Complex> bn = new ArrayList<>(); /* Initialization of the b(n) sequence (see Wikipedia's article above for the symbols * used)*/ for (int i = 0; i < bnSize; i++) { bn.add(new FFT.Complex()); } for (int i = 0; i < n; i++) { double angle = (i - n + 1) * (i - n + 1) * Math.PI / n * direction; bn.set(i, new FFT.Complex(Math.cos(angle), Math.sin(angle))); bn.set(bnSize - i - 1, new FFT.Complex(Math.cos(angle), Math.sin(angle))); } /* Initialization of the a(n) sequence */ for (int i = 0; i < n; i++) { double angle = -i * i * Math.PI / n * direction; an.add(x.get(i).multiply(new FFT.Complex(Math.cos(angle), Math.sin(angle)))); } ArrayList<FFT.Complex> convolution = ConvolutionFFT.convolutionFFT(an, bn); /* The final multiplication of the convolution with the b*(k) factor */ for (int i = 0; i < n; i++) { double angle = -1 * i * i * Math.PI / n * direction; FFT.Complex bk = new FFT.Complex(Math.cos(angle), Math.sin(angle)); x.set(i, bk.multiply(convolution.get(i + n - 1))); } /* Divide by n if we want the inverse FFT */ if (inverse) { for (int i = 0; i < n; i++) { FFT.Complex z = x.get(i); x.set(i, z.divide(n)); } } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java
src/main/java/com/thealgorithms/maths/SolovayStrassenPrimalityTest.java
package com.thealgorithms.maths; import java.util.Random; /** * This class implements the Solovay-Strassen primality test, * which is a probabilistic algorithm to determine whether a number is prime. * The algorithm is based on properties of the Jacobi symbol and modular exponentiation. * * For more information, go to {@link https://en.wikipedia.org/wiki/Solovay%E2%80%93Strassen_primality_test} */ final class SolovayStrassenPrimalityTest { private final Random random; /** * Constructs a SolovayStrassenPrimalityTest instance with a specified seed for randomness. * * @param seed the seed for generating random numbers */ private SolovayStrassenPrimalityTest(int seed) { random = new Random(seed); } /** * Factory method to create an instance of SolovayStrassenPrimalityTest. * * @param seed the seed for generating random numbers * @return a new instance of SolovayStrassenPrimalityTest */ public static SolovayStrassenPrimalityTest getSolovayStrassenPrimalityTest(int seed) { return new SolovayStrassenPrimalityTest(seed); } /** * Calculates modular exponentiation using the method of exponentiation by squaring. * * @param base the base number * @param exponent the exponent * @param mod the modulus * @return (base^exponent) mod mod */ private static long calculateModularExponentiation(long base, long exponent, long mod) { long x = 1; // This will hold the result of (base^exponent) % mod long y = base; // This holds the current base value being squared while (exponent > 0) { // If exponent is odd, multiply the current base (y) with x if (exponent % 2 == 1) { x = x * y % mod; // Update result with current base } // Square the base for the next iteration y = y * y % mod; // Update base to be y^2 exponent = exponent / 2; // Halve the exponent for next iteration } return x % mod; // Return final result after all iterations } /** * Computes the Jacobi symbol (a/n), which is a generalization of the Legendre symbol. * * @param a the numerator * @param num the denominator (must be an odd positive integer) * @return the Jacobi symbol value: 1, -1, or 0 */ public int calculateJacobi(long a, long num) { // Check if num is non-positive or even; Jacobi symbol is not defined in these cases if (num <= 0 || num % 2 == 0) { return 0; } a = a % num; // Reduce a modulo num to simplify calculations int jacobi = 1; // Initialize Jacobi symbol value while (a != 0) { // While a is even, reduce it and adjust jacobi based on properties of num while (a % 2 == 0) { a /= 2; // Divide a by 2 until it becomes odd long nMod8 = num % 8; // Get num modulo 8 to check conditions for jacobi adjustment if (nMod8 == 3 || nMod8 == 5) { jacobi = -jacobi; // Flip jacobi sign based on properties of num modulo 8 } } long temp = a; // Temporarily store value of a a = num; // Set a to be num for next iteration num = temp; // Set num to be previous value of a // Adjust jacobi based on properties of both numbers when both are odd and congruent to 3 modulo 4 if (a % 4 == 3 && num % 4 == 3) { jacobi = -jacobi; // Flip jacobi sign again based on congruences } a = a % num; // Reduce a modulo num for next iteration of Jacobi computation } return (num == 1) ? jacobi : 0; // If num reduces to 1, return jacobi value, otherwise return 0 (not defined) } /** * Performs the Solovay-Strassen primality test on a given number. * * @param num the number to be tested for primality * @param iterations the number of iterations to run for accuracy * @return true if num is likely prime, false if it is composite */ public boolean solovayStrassen(long num, int iterations) { if (num <= 1) { return false; // Numbers <=1 are not prime by definition. } if (num <= 3) { return true; // Numbers <=3 are prime. } for (int i = 0; i < iterations; i++) { long r = Math.abs(random.nextLong() % (num - 1)) + 2; // Generate a non-negative random number. long a = r % (num - 1) + 1; // Choose random 'a' in range [1, n-1]. long jacobi = (num + calculateJacobi(a, num)) % num; // Calculate Jacobi symbol and adjust it modulo n. long mod = calculateModularExponentiation(a, (num - 1) / 2, num); // Calculate modular exponentiation: a^((n-1)/2) mod n. if (jacobi == 0 || mod != jacobi) { return false; // If Jacobi symbol is zero or doesn't match modular result, n is composite. } } return true; // If no contradictions found after all iterations, n is likely prime. } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false