diff --git a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java index fbc095909541..e10559ae8a65 100644 --- a/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java +++ b/src/main/java/com/thealgorithms/audiofilters/IIRFilter.java @@ -2,7 +2,7 @@ /** * N-Order IIR Filter Assumes inputs are normalized to [-1, 1] - * + *
* Based on the difference equation from
* Wikipedia link
*/
diff --git a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
index 269880b8ddae..3471983f9c81 100644
--- a/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
+++ b/src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
@@ -41,7 +41,7 @@ public class AllPathsFromSourceToTarget {
private final int v;
// To store the paths from source to destination
- static List
* Output:
* {
* {'c', 'a', 't'},
diff --git a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
index 2c2da659f3aa..d2402151c45e 100644
--- a/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
+++ b/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
@@ -6,12 +6,12 @@
/**
* The KnightsTour class solves the Knight's Tour problem using backtracking.
- *
+ *
* Problem Statement:
* Given an N*N board with a knight placed on the first block, the knight must
* move according to chess rules and visit each square on the board exactly once.
* The class outputs the sequence of moves for the knight.
- *
+ *
* Example:
* Input: N = 8 (8x8 chess board)
* Output: The sequence of numbers representing the order in which the knight visits each square.
diff --git a/src/main/java/com/thealgorithms/backtracking/MColoring.java b/src/main/java/com/thealgorithms/backtracking/MColoring.java
index d0188dfd13aa..647ab4807302 100644
--- a/src/main/java/com/thealgorithms/backtracking/MColoring.java
+++ b/src/main/java/com/thealgorithms/backtracking/MColoring.java
@@ -10,11 +10,11 @@
* Node class represents a graph node. Each node is associated with a color
* (initially 1) and contains a set of edges representing its adjacent nodes.
*
- * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ * @author Bama Charan Chhandogi (...)
*/
class Node {
int color = 1; // Initial color for each node
- Set
* The goal is to find a path from a starting position to the target position
* (map[6][5]) while navigating through the maze.
*/
diff --git a/src/main/java/com/thealgorithms/backtracking/NQueens.java b/src/main/java/com/thealgorithms/backtracking/NQueens.java
index 404f677738a0..9b80256b3a45 100644
--- a/src/main/java/com/thealgorithms/backtracking/NQueens.java
+++ b/src/main/java/com/thealgorithms/backtracking/NQueens.java
@@ -10,21 +10,21 @@
* which N queens can be placed on the board such no two queens attack each
* other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....",
* "...Q..", ".....Q", "Q.....", "..Q...", "....Q."
- *
+ *
* Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.."
- *
+ *
* Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..."
- *
+ *
* Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...."
- *
+ *
* Solution: Brute Force approach:
- *
+ *
* Generate all possible arrangement to place N queens on N*N board. Check each
* board if queens are placed safely. If it is safe, include arrangement in
* solution set. Otherwise, ignore it
- *
+ *
* Optimized solution: This can be solved using backtracking in below steps
- *
+ *
* Start with first column and place queen on first row Try placing queen in a
* row on second column If placing second queen in second column attacks any of
* the previous queens, change the row in second column otherwise move to next
diff --git a/src/main/java/com/thealgorithms/backtracking/PowerSum.java b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
index b34ba660ebd7..67dd000636ee 100644
--- a/src/main/java/com/thealgorithms/backtracking/PowerSum.java
+++ b/src/main/java/com/thealgorithms/backtracking/PowerSum.java
@@ -6,7 +6,7 @@
* of unique, natural numbers.
* For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100.
* The only solution is 1^3 + 2^3 + 3^3 + 4^3. Therefore, the output will be 1.
- *
+ *
* N is represented by the parameter 'targetSum' in the code.
* X is represented by the parameter 'power' in the code.
*/
diff --git a/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java b/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java
index 4804e247ab03..9f282b76d33d 100644
--- a/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java
+++ b/src/main/java/com/thealgorithms/backtracking/UniquePermutation.java
@@ -6,11 +6,11 @@
/**
* Generates all UNIQUE permutations of a string, even when duplicate characters exist.
- *
+ *
* Example:
* Input: "AAB"
* Output: ["AAB", "ABA", "BAA"]
- *
+ *
* Time Complexity: O(n! * n)
*/
public final class UniquePermutation {
diff --git a/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java b/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java
index 1854cab20a7f..fbf53bffcca2 100644
--- a/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java
+++ b/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java
@@ -5,16 +5,16 @@
/**
* Class to determine if a pattern matches a string using backtracking.
- *
+ *
* Example:
* Pattern: "abab"
* Input String: "JavaPythonJavaPython"
* Output: true
- *
+ *
* Pattern: "aaaa"
* Input String: "JavaJavaJavaJava"
* Output: true
- *
+ *
* Pattern: "aabb"
* Input String: "JavaPythonPythonJava"
* Output: false
diff --git a/src/main/java/com/thealgorithms/backtracking/WordSearch.java b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
index 452f17b6ace6..ddb8b8baf4d6 100644
--- a/src/main/java/com/thealgorithms/backtracking/WordSearch.java
+++ b/src/main/java/com/thealgorithms/backtracking/WordSearch.java
@@ -2,12 +2,12 @@
/**
* Word Search Problem
- *
+ *
* This class solves the word search problem where given an m x n grid of characters (board)
* and a target word, the task is to check if the word exists in the grid.
* The word can be constructed from sequentially adjacent cells (horizontally or vertically),
* and the same cell may not be used more than once in constructing the word.
- *
+ *
* Example:
* - For board =
* [
@@ -18,19 +18,19 @@
* and word = "ABCCED", -> returns true
* and word = "SEE", -> returns true
* and word = "ABCB", -> returns false
- *
+ *
* Solution:
* - Depth First Search (DFS) with backtracking is used to explore possible paths from any cell
* matching the first letter of the word. DFS ensures that we search all valid paths, while
* backtracking helps in reverting decisions when a path fails to lead to a solution.
- *
+ *
* Time Complexity: O(m * n * 3^L)
* - m = number of rows in the board
* - n = number of columns in the board
* - L = length of the word
* - For each cell, we look at 3 possible directions (since we exclude the previously visited direction),
* and we do this for L letters.
- *
+ *
* Space Complexity: O(L)
* - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word).
*/
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java
index e6bd35720d9f..75d4e8300757 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java
@@ -2,12 +2,12 @@
/**
* This class provides methods to convert between BCD (Binary-Coded Decimal) and decimal numbers.
- *
+ *
* BCD is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of binary digits, usually four or eight.
- *
+ *
* For more information, refer to the
* Binary-Coded Decimal Wikipedia page.
- *
+ *
* Example usage:
*
* Example:
* 26 (11010) -> 10 (01010)
* 1 (1) -> 0 (0)
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java b/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java
index 8d2c757e5e0a..97f381ff87f5 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java
@@ -2,16 +2,16 @@
/**
* Implementation to count number of bits to be flipped to convert A to B
- *
+ *
* Problem: Given two numbers A and B, count the number of bits needed to be
* flipped to convert A to B.
- *
+ *
* Example:
* A = 10 (01010 in binary)
* B = 20 (10100 in binary)
* XOR = 30 (11110 in binary) - positions where bits differ
* Answer: 4 bits need to be flipped
- *
+ *
* Time Complexity: O(log n) - where n is the number of set bits
* Space Complexity: O(1)
*
@@ -25,7 +25,7 @@ private CountBitsFlip() {
/**
* Counts the number of bits that need to be flipped to convert a to b
- *
+ *
* Algorithm:
* 1. XOR a and b to get positions where bits differ
* 2. Count the number of set bits in the XOR result
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java
index 9a761c572e2c..b9f8c0d6d43e 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java
@@ -3,7 +3,7 @@
/**
* This class provides a method to find the first differing bit
* between two integers.
- *
+ *
* Example:
* x = 10 (1010 in binary)
* y = 12 (1100 in binary)
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java
index 2398b8214371..a0e26f4cb2ff 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java
@@ -4,12 +4,12 @@
/**
* Find Highest Set Bit
- *
+ *
* This class provides a utility method to calculate the position of the highest
* (most significant) bit that is set to 1 in a given non-negative integer.
* It is often used in bit manipulation tasks to find the left-most set bit in binary
* representation of a number.
- *
+ *
* Example:
* - For input 18 (binary 10010), the highest set bit is at position 4 (zero-based index).
*
@@ -25,7 +25,7 @@ private HighestSetBit() {
/**
* Finds the highest (most significant) set bit in the given integer.
* The method returns the position (index) of the highest set bit as an {@link Optional}.
- *
+ *
* - If the number is 0, no bits are set, and the method returns {@link Optional#empty()}.
* - If the number is negative, the method throws {@link IllegalArgumentException}.
*
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java
index 1b8962344ea7..cfb3837ed42d 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java
@@ -6,8 +6,8 @@
* Specifically, it includes a method to find the index of the rightmost set bit
* in an integer.
* This class is not meant to be instantiated.
- *
- * Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ *
+ * Author: Bama Charan Chhando(https://github.com/BamaCharanChhandogi)
*/
public final class IndexOfRightMostSetBit {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java
index 09d5383322ff..234458aa41c0 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java
@@ -2,7 +2,7 @@
/**
* Checks whether a number is even
- * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ * @author Bama Charan Chhandogi (...)
*/
public final class IsEven {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java
index 4cdf3c6faa3e..6807f34a6e07 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java
@@ -5,7 +5,7 @@
* A power of two is a number that can be expressed as 2^n where n is a non-negative integer.
* This class provides a method to determine if a given integer is a power of two using bit manipulation.
*
- * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ * @author Bama Charan Chhandogi (...)
*/
public final class IsPowerTwo {
private IsPowerTwo() {
@@ -13,7 +13,7 @@ private IsPowerTwo() {
/**
* Checks if the given integer is a power of two.
- *
+ *
* A number is considered a power of two if it is greater than zero and
* has exactly one '1' bit in its binary representation. This method
* uses the property that for any power of two (n), the expression
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java
index 127b6fa2c0b1..3b4d148a5cb9 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java
@@ -2,7 +2,7 @@
/**
* Lowest Set Bit
- * @author Prayas Kumar (https://github.com/prayas7102)
+ * @author Prayas Kumar (...)
*/
public final class LowestSetBit {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java
index 17e1a73ec062..e167f94a06a6 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java
@@ -3,17 +3,17 @@
/**
* A utility class to find the non-repeating number in an array where every other number repeats.
* This class contains a method to identify the single unique number using bit manipulation.
- *
+ *
* The solution leverages the properties of the XOR operation, which states that:
* - x ^ x = 0 for any integer x (a number XORed with itself is zero)
* - x ^ 0 = x for any integer x (a number XORed with zero is the number itself)
- *
+ *
* Using these properties, we can find the non-repeating number in linear time with constant space.
- *
+ *
* Example:
* Given the input array [2, 3, 5, 2, 3], the output will be 5 since it does not repeat.
*
- * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
+ * @author Bama Charan...ranChhandogi)
*/
public final class NonRepeatingNumberFinder {
private NonRepeatingNumberFinder() {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java
index bd4868d4dbd5..88d5f051bd72 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java
@@ -4,20 +4,20 @@
* This class provides a method to find the element that appears an
* odd number of times in an array. All other elements in the array
* must appear an even number of times for the logic to work.
- *
+ *
* The solution uses the XOR operation, which has the following properties:
* - a ^ a = 0 (XOR-ing the same numbers cancels them out)
* - a ^ 0 = a
* - XOR is commutative and associative.
- *
+ *
* Time Complexity: O(n), where n is the size of the array.
* Space Complexity: O(1), as no extra space is used.
- *
+ *
* Usage Example:
* int result = NumberAppearingOddTimes.findOddOccurrence(new int[]{1, 2, 1, 2, 3});
* // result will be 3
*
- * @author Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999)
+ * @author Lakshyajeet SGoyal (https://github.com/DarkMatter-999)
*/
public final class NumberAppearingOddTimes {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java b/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java
index a2da37aa81ee..128775dba000 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java
@@ -3,11 +3,11 @@
/**
* This class provides a method to determine whether two integers have
* different signs. It utilizes the XOR operation on the two numbers:
- *
+ *
* - If two numbers have different signs, their most significant bits
* (sign bits) will differ, resulting in a negative XOR result.
* - If two numbers have the same sign, the XOR result will be non-negative.
- *
+ *
* Time Complexity: O(1) - Constant time operation.
* Space Complexity: O(1) - No extra space used.
*
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java b/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java
index afec0188e299..3324cb1fef73 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java
@@ -3,7 +3,7 @@
/**
* This class provides a method to detect if two integers
* differ by exactly one bit flip.
- *
+ *
* Example:
* 1 (0001) and 2 (0010) differ by exactly one bit flip.
* 7 (0111) and 3 (0011) differ by exactly one bit flip.
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java
index aae3a996e49d..97908141618b 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java
@@ -1,8 +1,8 @@
package com.thealgorithms.bitmanipulation;
/**
- * @author - https://github.com/Monk-AbhinayVerma
- * @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement
+ * @author - ...
+ * @Wikipedia - ...
* The class OnesComplement computes the complement of binary number
* and returns
* the complemented binary string.
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java
index 12c269d9be48..56c97e7322d3 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java
@@ -4,14 +4,14 @@
* This class provides a method to reverse the bits of a 32-bit integer.
* Reversing the bits means that the least significant bit (LSB) becomes
* the most significant bit (MSB) and vice versa.
- *
+ *
* Example:
* Input (binary): 00000010100101000001111010011100 (43261596)
* Output (binary): 00111001011110000010100101000000 (964176192)
- *
+ *
* Time Complexity: O(32) - A fixed number of 32 iterations
* Space Complexity: O(1) - No extra space used
- *
+ *
* Note:
* - If the input is negative, Java handles it using two’s complement representation.
* - This function works on 32-bit integers by default.
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java
index 624a4e2b858a..98f5d867777a 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java
@@ -4,19 +4,19 @@
* A utility class for performing single-bit operations on integers.
* These operations include flipping, setting, clearing, and getting
* individual bits at specified positions.
- *
+ *
* Bit positions are zero-indexed (i.e., the least significant bit is at position 0).
* These methods leverage bitwise operations for optimal performance.
- *
+ *
* Examples:
* - `flipBit(3, 1)` flips the bit at index 1 in binary `11` (result: `1`).
* - `setBit(4, 0)` sets the bit at index 0 in `100` (result: `101` or 5).
* - `clearBit(7, 1)` clears the bit at index 1 in `111` (result: `101` or 5).
* - `getBit(6, 0)` checks if the least significant bit is set (result: `0`).
- *
+ *
* Time Complexity: O(1) for all operations.
- *
- * Author: lukasb1b (https://github.com/lukasb1b)
+ *
+ * Aulukasb1b (https://github.com/lukasb1b)
*/
public final class SingleBitOperations {
private SingleBitOperations() {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java
index 98a7de8bdf1a..694acea67d36 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java
@@ -3,11 +3,11 @@
/**
* A utility class to swap every pair of adjacent bits in a given integer.
* This operation shifts the even-positioned bits to odd positions and vice versa.
- *
+ *
* Example:
* - Input: 2 (binary: `10`) → Output: 1 (binary: `01`)
* - Input: 43 (binary: `101011`) → Output: 23 (binary: `010111`)
- *
+ *
* **Explanation of the Algorithm:**
* 1. Mask even-positioned bits: Using `0xAAAAAAAA` (binary: `101010...`),
* which selects bits in even positions.
@@ -17,13 +17,13 @@
* - Right-shift even-positioned bits by 1 to move them to odd positions.
* - Left-shift odd-positioned bits by 1 to move them to even positions.
* 4. Combine both shifted results using bitwise OR (`|`) to produce the final result.
- *
+ *
* Use Case: This algorithm can be useful in applications involving low-level bit manipulation,
* such as encoding, data compression, or cryptographic transformations.
- *
+ *
* Time Complexity: O(1) (constant time, since operations are bitwise).
- *
- * Author: Lakshyajeet Singh Goyal (https://github.com/DarkMatter-999)
+ *
+ * Author: LakshSingh Goyal (https://github.com/DarkMatter-999)
*/
public final class SwapAdjacentBits {
private SwapAdjacentBits() {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java
index 9b8cecd791a6..146a3cf5cb4c 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java
@@ -13,7 +13,7 @@
*
* Algorithm originally suggested by Jon von Neumann.
*
- * @author Abhinay Verma (https://github.com/Monk-AbhinayVerma)
+ * @author Abhinay Verma (...)
*/
public final class TwosComplement {
private TwosComplement() {
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java b/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java
index b22abc0c04ff..1b8a1b7252eb 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java
@@ -2,12 +2,12 @@
/**
* This class provides methods to convert between XS-3 (Excess-3) and binary.
- *
+ *
* Excess-3, also called XS-3, is a binary-coded decimal (BCD) code in which each decimal digit is represented by its corresponding 4-bit binary value plus 3.
- *
+ *
* For more information, refer to the
* Excess-3 Wikipedia page.
- *
+ *
* Example usage:
*
* E(x) = (a * x + b) mod m
* D(y) = a^-1 * (y - b) mod m
- *
+ *
* where:
* - E(x) is the encrypted character,
* - D(y) is the decrypted character,
@@ -15,7 +15,7 @@
* - x is the index of the plaintext character,
* - y is the index of the ciphertext character,
* - m is the size of the alphabet (26 for the English alphabet).
- *
+ *
* The class provides methods for encrypting and decrypting messages, as well as a main method to demonstrate its usage.
*/
final class AffineCipher {
@@ -23,8 +23,8 @@ private AffineCipher() {
}
// Key values of a and b
- static int a = 17;
- static int b = 20;
+ static final int a = 17;
+ static final int b = 20;
/**
* Encrypts a message using the Affine cipher.
diff --git a/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java b/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java
index 9169aa82bd75..8b9b48dad06d 100644
--- a/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/AtbashCipher.java
@@ -3,14 +3,14 @@
/**
* The Atbash cipher is a classic substitution cipher that substitutes each letter
* with its opposite letter in the alphabet.
- *
+ *
* For example:
* - 'A' becomes 'Z', 'B' becomes 'Y', 'C' becomes 'X', and so on.
* - Similarly, 'a' becomes 'z', 'b' becomes 'y', and so on.
- *
+ *
* The cipher works identically for both uppercase and lowercase letters.
* Non-alphabetical characters remain unchanged in the output.
- *
+ *
* This cipher is symmetric, meaning that applying the cipher twice will return
* the original text. Therefore, the same function is used for both encryption and decryption.
*
diff --git a/src/main/java/com/thealgorithms/ciphers/Autokey.java b/src/main/java/com/thealgorithms/ciphers/Autokey.java
index bb67f512accf..3a07a9328c78 100644
--- a/src/main/java/com/thealgorithms/ciphers/Autokey.java
+++ b/src/main/java/com/thealgorithms/ciphers/Autokey.java
@@ -5,7 +5,7 @@
* as it improves upon the classic Vigenère Cipher by using the plaintext itself to
* extend the key. This makes it harder to break using frequency analysis, as it
* doesn’t rely solely on a repeated key.
- * https://en.wikipedia.org/wiki/Autokey_cipher
+ * ...
*
* @author bennybebo
*/
diff --git a/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java b/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java
index 16dfd6e674af..945cc372499a 100644
--- a/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/BaconianCipher.java
@@ -7,7 +7,7 @@
* The Baconian Cipher is a substitution cipher where each letter is represented
* by a group of five binary digits (A's and B's). It can also be used to hide
* messages within other texts, making it a simple form of steganography.
- * https://en.wikipedia.org/wiki/Bacon%27s_cipher
+ * ...
*
* @author Bennybebo
*/
diff --git a/src/main/java/com/thealgorithms/ciphers/Blowfish.java b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
index ea1807e62710..33439c6c199a 100644
--- a/src/main/java/com/thealgorithms/ciphers/Blowfish.java
+++ b/src/main/java/com/thealgorithms/ciphers/Blowfish.java
@@ -11,7 +11,7 @@
public class Blowfish {
// Initializing substitution boxes
- String[][] sBox = {
+ final String[][] sBox = {
{
"d1310ba6",
"98dfb5ac",
@@ -1047,7 +1047,7 @@ public class Blowfish {
};
// Initializing subkeys with digits of pi
- String[] subKeys = {
+ final String[] subKeys = {
"243f6a88",
"85a308d3",
"13198a2e",
@@ -1069,7 +1069,7 @@ public class Blowfish {
};
// Initializing modVal to 2^32
- long modVal = 4294967296L;
+ final long modVal = 4294967296L;
/**
* This method returns binary representation of the hexadecimal number passed as parameter
@@ -1115,7 +1115,7 @@ private String binToHex(String binary) {
* This method returns a string obtained by XOR-ing two strings of same length passed a method
* parameters
*
- * @param String a and b are string objects which will be XORed and are to be of same length
+ * @param a and @param b are string objects which will be XORed and are to be of same length
* @return String object obtained by XOR operation on String a and String b
* */
private String xor(String a, String b) {
@@ -1133,12 +1133,13 @@ private String xor(String a, String b) {
* This method returns addition of two hexadecimal numbers passed as parameters and moded with
* 2^32
*
- * @param String a and b are hexadecimal numbers
+ * @param a hexadecimal number
+ * @param b hexadecimal number
* @return String object which is a is addition that is then moded with 2^32 of hex numbers
* passed as parameters
*/
private String addBin(String a, String b) {
- String ans = "";
+ String ans;
long n1 = Long.parseUnsignedLong(a, 16);
long n2 = Long.parseUnsignedLong(b, 16);
n1 = (n1 + n2) % modVal;
@@ -1154,7 +1155,7 @@ private String addBin(String a, String b) {
*/
private String f(String plainText) {
String[] a = new String[4];
- String ans = "";
+ String ans;
for (int i = 0; i < 8; i += 2) {
// column number for S-box is a 8-bit value
long col = Long.parseUnsignedLong(hexToBin(plainText.substring(i, i + 2)), 2);
@@ -1198,8 +1199,8 @@ private String round(int time, String plainText) {
* This method returns cipher text for the plaintext passed as the first parameter generated
* using the key passed as the second parameter
*
- * @param String plainText is the text which is to be encrypted
- * @param String key is the key which is to be used for generating cipher text
+ * @param plainText is the text which is to be encrypted
+ * @param key is the key which is to be used for generating cipher text
* @return String cipherText is the encrypted value
*/
String encrypt(String plainText, String key) {
@@ -1222,8 +1223,8 @@ String encrypt(String plainText, String key) {
* This method returns plaintext for the ciphertext passed as the first parameter decoded
* using the key passed as the second parameter
*
- * @param String ciphertext is the text which is to be decrypted
- * @param String key is the key which is to be used for generating cipher text
+ * @param cipherText is the text which is to be decrypted
+ * @param key is the key which is to be used for generating cipher text
* @return String plainText is the decrypted text
*/
String decrypt(String cipherText, String key) {
diff --git a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
index b6b889b079ca..4bf1d121d498 100644
--- a/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/ColumnarTranspositionCipher.java
@@ -80,7 +80,7 @@ public static String decrypt() {
wordDecrypted.append(item);
}
}
- return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, "");
+ return wordDecrypted.toString().replace(ENCRYPTION_FIELD, "");
}
/**
diff --git a/src/main/java/com/thealgorithms/ciphers/DES.java b/src/main/java/com/thealgorithms/ciphers/DES.java
index 7f3eed70f3c2..a8d534b15cd2 100644
--- a/src/main/java/com/thealgorithms/ciphers/DES.java
+++ b/src/main/java/com/thealgorithms/ciphers/DES.java
@@ -2,7 +2,7 @@
/**
* This class is build to demonstrate the application of the DES-algorithm
- * (https://en.wikipedia.org/wiki/Data_Encryption_Standard) on a plain English message. The supplied
+ * (...) on a plain English message. The supplied
* key must be in form of a 64 bit binary String.
*/
public class DES {
diff --git a/src/main/java/com/thealgorithms/ciphers/ECC.java b/src/main/java/com/thealgorithms/ciphers/ECC.java
index 7b1e37f0e1e1..e6225c345bd6 100644
--- a/src/main/java/com/thealgorithms/ciphers/ECC.java
+++ b/src/main/java/com/thealgorithms/ciphers/ECC.java
@@ -9,7 +9,7 @@
* elliptic curves over finite fields. ECC provides a higher level of security with smaller key sizes compared
* to other public-key methods like RSA, making it particularly suitable for environments where computational
* resources are limited, such as mobile devices and embedded systems.
- *
+ *
* This class implements elliptic curve cryptography, providing encryption and decryption
* functionalities based on public and private key pairs.
*
diff --git a/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java b/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java
index ce443545db1d..686dfb3e4219 100644
--- a/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/PermutationCipher.java
@@ -7,7 +7,7 @@
* A Java implementation of Permutation Cipher.
* It is a type of transposition cipher in which the plaintext is divided into blocks
* and the characters within each block are rearranged according to a fixed permutation key.
- *
+ *
* For example, with key {3, 1, 2} and plaintext "HELLO", the text is divided into blocks
* of 3 characters: "HEL" and "LO" (with padding). The characters are then rearranged
* according to the key positions.
diff --git a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java
index 76ceb6dbce31..003373036e0d 100644
--- a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java
@@ -3,7 +3,7 @@
public class PlayfairCipher {
private char[][] matrix;
- private String key;
+ private final String key;
public PlayfairCipher(String key) {
this.key = key;
diff --git a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
index d7eaea757001..01307642562a 100644
--- a/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/ProductCipher.java
@@ -2,72 +2,162 @@
import java.util.Scanner;
+/**
+ * ProductCipher combines substitution and transposition ciphers.
+ * Refactoring notes:
+ * - SRP: encryption, decryption, padding, and I/O are each in their own method.
+ * - OCP/DIP: SubstitutionCipher and TranspositionCipher implement the Cipher
+ * interface, so new cipher types can be added without touching existing code.
+ * - StringBuffer replaced with StringBuilder (thread-safety not needed here).
+ * - Magic number 5 (Caesar shift) extracted to a named constant.
+ * - The `n` variable is no longer reused for two different purposes.
+ * - God-method main() now delegates to focused, testable helpers.
+ */
final class ProductCipher {
+
private ProductCipher() {
}
- public static void main(String[] args) {
- try (Scanner sc = new Scanner(System.in)) {
- System.out.println("Enter the input to be encrypted: ");
- String substitutionInput = sc.nextLine();
- System.out.println(" ");
- System.out.println("Enter a number: ");
- int n = sc.nextInt();
-
- // Substitution encryption
- StringBuffer substitutionOutput = new StringBuffer();
- for (int i = 0; i < substitutionInput.length(); i++) {
- char c = substitutionInput.charAt(i);
- substitutionOutput.append((char) (c + 5));
+ // ------------------------------------------------------------------ //
+ // Cipher abstraction (Open/Closed + Dependency-Inversion principles) //
+ // ------------------------------------------------------------------ //
+
+ interface Cipher {
+ String encrypt(String input, int key);
+ String decrypt(String input, int key);
+ }
+
+ // ------------------------------------------------------------------ //
+ // Substitution cipher //
+ // ------------------------------------------------------------------ //
+
+ static final class SubstitutionCipher implements Cipher {
+
+ private static final int SHIFT = 5;
+
+ @Override
+ public String encrypt(String input, int key) {
+ // `key` is unused for a fixed-shift substitution cipher,
+ // but kept in the signature to satisfy the Cipher contract.
+ StringBuilder result = new StringBuilder(input.length());
+ for (char c : input.toCharArray()) {
+ result.append((char) (c + SHIFT));
}
- System.out.println(" ");
- System.out.println("Substituted text: ");
- System.out.println(substitutionOutput);
-
- // Transposition encryption
- String transpositionInput = substitutionOutput.toString();
- int modulus = transpositionInput.length() % n;
- if (modulus != 0) {
- modulus = n - modulus;
-
- for (; modulus != 0; modulus--) {
- transpositionInput += "/";
- }
+ return result.toString();
+ }
+
+ @Override
+ public String decrypt(String input, int key) {
+ StringBuilder result = new StringBuilder(input.length());
+ for (char c : input.toCharArray()) {
+ result.append((char) (c - SHIFT));
+ }
+ return result.toString();
+ }
+ }
+
+ // ------------------------------------------------------------------ //
+ // Transposition cipher //
+ // ------------------------------------------------------------------ //
+
+ static final class TranspositionCipher implements Cipher {
+
+ private static final char PAD_CHAR = '/';
+
+ /** Pad the text so its length is a multiple of {@code numRows}. */
+ String pad(String text, int numRows) {
+ int remainder = text.length() % numRows;
+ if (remainder == 0) {
+ return text;
}
- StringBuffer transpositionOutput = new StringBuffer();
- System.out.println(" ");
+ int paddingNeeded = numRows - remainder;
+ StringBuilder padded = new StringBuilder(text);
+ padded.repeat(String.valueOf(PAD_CHAR), Math.max(0, paddingNeeded));
+ return padded.toString();
+ }
+
+ /**
+ * Reads the padded text column-by-column (row-major write, column-major read).
+ * Prints the transposition matrix as a `side effect for traceability.
+ */
+ @Override
+ public String encrypt(String input, int numRows) {
+ String padded = pad(input, numRows);
+ int numCols = padded.length() / numRows;
+
System.out.println("Transposition Matrix: ");
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < transpositionInput.length() / n; j++) {
- char c = transpositionInput.charAt(i + (j * n));
+ StringBuilder result = new StringBuilder(padded.length());
+
+ for (int row = 0; row < numRows; row++) {
+ for (int col = 0; col < numCols; col++) {
+ char c = padded.charAt(row + col * numRows);
System.out.print(c);
- transpositionOutput.append(c);
+ result.append(c);
}
System.out.println();
}
- System.out.println(" ");
- System.out.println("Final encrypted text: ");
- System.out.println(transpositionOutput);
-
- // Transposition decryption
- n = transpositionOutput.length() / n;
- StringBuffer transpositionPlaintext = new StringBuffer();
- for (int i = 0; i < n; i++) {
- for (int j = 0; j < transpositionOutput.length() / n; j++) {
- char c = transpositionOutput.charAt(i + (j * n));
- transpositionPlaintext.append(c);
+
+ return result.toString();
+ }
+
+ /** Reverses the column-major read by treating the cipher as row-major. */
+ @Override
+ public String decrypt(String input, int numRows) {
+ int numCols = input.length() / numRows;
+ StringBuilder result = new StringBuilder(input.length());
+
+ for (int row = 0; row < numCols; row++) {
+ for (int col = 0; col < numRows; col++) {
+ result.append(input.charAt(row + col * numCols));
}
}
+ return result.toString();
+ }
+ }
- // Substitution decryption
- StringBuffer plaintext = new StringBuffer();
- for (int i = 0; i < transpositionPlaintext.length(); i++) {
- char c = transpositionPlaintext.charAt(i);
- plaintext.append((char) (c - 5));
- }
+ // ------------------------------------------------------------------ //
+ // I/O helper (Single-Responsibility: only reads user input) //
+ // ------------------------------------------------------------------ //
+
+ private static String readPlaintext(Scanner sc) {
+ System.out.println("Enter the input to be encrypted: ");
+ return sc.nextLine();
+ }
+
+ private static int readKey(Scanner sc) {
+ System.out.println("Enter a number: ");
+ return sc.nextInt();
+ }
+
+ // ------------------------------------------------------------------ //
+ // Entry point – thin orchestration only //
+ // ------------------------------------------------------------------ //
+
+ public static void main(String[] args) {
+ Cipher substitution = new SubstitutionCipher();
+ Cipher transposition = new TranspositionCipher();
+
+ try (Scanner sc = new Scanner(System.in)) {
+ String plaintext = readPlaintext(sc);
+ int key = readKey(sc);
+
+ // Encrypt
+ String afterSubstitution = substitution.encrypt(plaintext, key);
+ System.out.println("\nSubstituted text: ");
+ System.out.println(afterSubstitution);
+
+ System.out.println();
+ String ciphertext = transposition.encrypt(afterSubstitution, key);
+ System.out.println("\nFinal encrypted text: ");
+ System.out.println(ciphertext);
+
+ // Decrypt (use a separate variable; never reuse `key` for a different meaning)
+ int decryptionKey = ciphertext.length() / key;
+ String afterTranspositionDecrypt = transposition.decrypt(ciphertext, decryptionKey);
+ String recovered = substitution.decrypt(afterTranspositionDecrypt, key);
System.out.println("Plaintext: ");
- System.out.println(plaintext);
+ System.out.println(recovered);
}
}
-}
+}
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/ciphers/RSA.java b/src/main/java/com/thealgorithms/ciphers/RSA.java
index 28af1a62032a..8c6242ecb68e 100644
--- a/src/main/java/com/thealgorithms/ciphers/RSA.java
+++ b/src/main/java/com/thealgorithms/ciphers/RSA.java
@@ -7,11 +7,11 @@
* RSA is an asymmetric cryptographic algorithm used for secure data encryption and decryption.
* It relies on a pair of keys: a public key (used for encryption) and a private key
* (used for decryption). The algorithm is based on the difficulty of factoring large prime numbers.
- *
+ *
* This implementation includes key generation, encryption, and decryption methods that can handle both
* text-based messages and BigInteger inputs. For more details on RSA:
* RSA Cryptosystem - Wikipedia.
- *
+ *
* Example Usage:
*
* The Vigenère Cipher is a polyalphabetic substitution cipher that uses a
* keyword to shift letters in the plaintext by different amounts, depending
* on the corresponding character in the keyword. It wraps around the alphabet,
* ensuring the shifts are within 'A'-'Z' or 'a'-'z'.
- *
+ *
* Non-alphabetic characters (like spaces, punctuation) are kept unchanged.
- *
+ *
* Encryption Example:
* - Plaintext: "Hello World!"
* - Key: "suchsecret"
* - Encrypted Text: "Zynsg Yfvev!"
- *
+ *
* Decryption Example:
* - Ciphertext: "Zynsg Yfvev!"
* - Key: "suchsecret"
* - Decrypted Text: "Hello World!"
- *
+ *
* Wikipedia Reference:
* Vigenère Cipher - Wikipedia
*
diff --git a/src/main/java/com/thealgorithms/ciphers/XORCipher.java b/src/main/java/com/thealgorithms/ciphers/XORCipher.java
index a612ccfbcdef..9070255b9c1d 100644
--- a/src/main/java/com/thealgorithms/ciphers/XORCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/XORCipher.java
@@ -9,22 +9,22 @@
* using a given key. This cipher works by applying the XOR bitwise operation between
* the bytes of the input text and the corresponding bytes of the key (repeating the key
* if necessary).
- *
+ *
* Usage:
* - Encryption: Converts plaintext into a hexadecimal-encoded ciphertext.
* - Decryption: Converts the hexadecimal ciphertext back into plaintext.
- *
+ *
* Characteristics:
* - Symmetric: The same key is used for both encryption and decryption.
* - Simple but vulnerable: XOR encryption is insecure for real-world cryptography,
* especially when the same key is reused.
- *
+ *
* Example:
* Plaintext: "Hello!"
* Key: "key"
* Encrypted: "27090c03120b"
* Decrypted: "Hello!"
- *
+ *
* Reference: XOR Cipher - Wikipedia
*
* @author lcsjunior
diff --git a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
index cc2e9105229a..0e39c7a9ea81 100644
--- a/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/a5/A5Cipher.java
@@ -5,7 +5,7 @@
/**
* The A5Cipher class implements the A5/1 stream cipher, which is a widely used
* encryption algorithm, particularly in mobile communications.
- *
+ *
* This implementation uses a key stream generator to produce a stream of bits
* that are XORed with the plaintext bits to produce the ciphertext.
*
@@ -32,7 +32,7 @@ public A5Cipher(BitSet sessionKey, BitSet frameCounter) {
/**
* Encrypts the given plaintext bits using the A5/1 cipher algorithm.
- *
+ *
* This method generates a key stream and XORs it with the provided plaintext
* bits to produce the ciphertext.
*
@@ -52,7 +52,7 @@ public BitSet encrypt(BitSet plainTextBits) {
/**
* Resets the internal counter of the key stream generator.
- *
+ *
* This method can be called to re-initialize the state of the key stream
* generator, allowing for new key streams to be generated for subsequent
* encryptions.
diff --git a/src/main/java/com/thealgorithms/compression/LZ78.java b/src/main/java/com/thealgorithms/compression/LZ78.java
index 904c379cc2a2..28fdd50d521f 100644
--- a/src/main/java/com/thealgorithms/compression/LZ78.java
+++ b/src/main/java/com/thealgorithms/compression/LZ78.java
@@ -55,7 +55,7 @@ public record Token(int index, char nextChar) {
* Each node represents a phrase and can have child nodes for extended phrases.
*/
private static final class TrieNode {
- Map
* This class supports inversion and composition of affine transformations.
* It is immutable, meaning each instance represents a fixed transformation.
*/
diff --git a/src/main/java/com/thealgorithms/conversions/AnytoAny.java b/src/main/java/com/thealgorithms/conversions/AnytoAny.java
index e7bdbc2b79c4..06ba653af076 100644
--- a/src/main/java/com/thealgorithms/conversions/AnytoAny.java
+++ b/src/main/java/com/thealgorithms/conversions/AnytoAny.java
@@ -2,7 +2,7 @@
/**
* A utility class for converting numbers from any base to any other base.
- *
+ *
* This class provides a method to convert a source number from a given base
* to a destination number in another base. Valid bases range from 2 to 10.
*/
diff --git a/src/main/java/com/thealgorithms/conversions/Base64.java b/src/main/java/com/thealgorithms/conversions/Base64.java
index 5219c4ba7f4e..aebca161839f 100644
--- a/src/main/java/com/thealgorithms/conversions/Base64.java
+++ b/src/main/java/com/thealgorithms/conversions/Base64.java
@@ -8,14 +8,14 @@
* Base64 is a group of binary-to-text encoding schemes that represent binary data
* in an ASCII string format by translating it into a radix-64 representation.
* Each base64 digit represents exactly 6 bits of data.
- *
+ *
* Base64 encoding is commonly used when there is a need to encode binary data
* that needs to be stored and transferred over media that are designed to deal
* with textual data.
- *
- * Wikipedia Reference: https://en.wikipedia.org/wiki/Base64
+ *
+ * Wikipedia Refhttps://en.wikipedia.org/wiki/Base64
* Author: Nithin U.
- * Github: https://github.com/NithinU2802
+ * https://github.com/NithinU2802
*/
public final class Base64 {
diff --git a/src/main/java/com/thealgorithms/conversions/IPConverter.java b/src/main/java/com/thealgorithms/conversions/IPConverter.java
index 765cb0201dd5..21821553933d 100644
--- a/src/main/java/com/thealgorithms/conversions/IPConverter.java
+++ b/src/main/java/com/thealgorithms/conversions/IPConverter.java
@@ -4,7 +4,7 @@
* Converts an IPv4 address to its binary equivalent and vice-versa.
* IP to Binary: Converts an IPv4 address to its binary equivalent.
* Example: 127.3.4.5 -> 01111111.00000011.00000100.00000101
- *
+ *
* Binary to IP: Converts a binary equivalent to an IPv4 address.
* Example: 01111111.00000011.00000100.00000101 -> 127.3.4.5
*
diff --git a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
index d42ffd027514..bf13e5597cff 100644
--- a/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
+++ b/src/main/java/com/thealgorithms/conversions/IPv6Converter.java
@@ -6,7 +6,7 @@
/**
* A utility class for converting between IPv6 and IPv4 addresses.
- *
+ *
* - Converts IPv4 to IPv6-mapped IPv6 address.
* - Extracts IPv4 address from IPv6-mapped IPv6.
* - Handles exceptions for invalid inputs.
diff --git a/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java b/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java
index e85c608af5d0..85168d0d9587 100644
--- a/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java
+++ b/src/main/java/com/thealgorithms/conversions/IntegerToEnglish.java
@@ -60,7 +60,7 @@ private static String convertToWords(int number) {
int hundredsDigit = number / 100;
if (hundredsDigit > 0) {
- if (result.length() > 0) {
+ if (!result.isEmpty()) {
result.insert(0, " ");
}
result.insert(0, String.format("%s Hundred", BASE_NUMBERS_MAP.get(hundredsDigit)));
@@ -93,7 +93,7 @@ public static String integerToEnglishWords(int number) {
if (index > 0) {
subResult += " " + THOUSAND_POWER_MAP.get(index);
}
- if (result.length() > 0) {
+ if (!result.isEmpty()) {
result.insert(0, " ");
}
result.insert(0, subResult);
diff --git a/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
index a3973da0c586..383ffe334bef 100644
--- a/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
+++ b/src/main/java/com/thealgorithms/conversions/MorseCodeConverter.java
@@ -7,10 +7,10 @@
* Converts text to Morse code and vice-versa.
* Text to Morse code: Each letter is separated by a space and each word is separated by a pipe (|).
* Example: "HELLO WORLD" -> ".... . .-.. .-.. --- | .-- --- .-. .-.. -.."
- *
+ *
* Morse code to text: Each letter is separated by a space and each word is separated by a pipe (|).
* Example: ".... . .-.. .-.. --- | .-- --- .-. .-.. -.." -> "HELLO WORLD"
- *
+ *
* Applications: Used in radio communications and algorithmic challenges.
*
* @author Hardvan
diff --git a/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java b/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java
index 901db17c665d..b9dd2315bc96 100644
--- a/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java
+++ b/src/main/java/com/thealgorithms/conversions/TemperatureConverter.java
@@ -12,7 +12,7 @@
*
* This class is final and cannot be instantiated.
*
- * @author krishna-medapati (https://github.com/krishna-medapati)
+ * @author krishna-medapati (...)
* @see Wikipedia: Temperature Conversion
*/
public final class TemperatureConverter {
diff --git a/src/main/java/com/thealgorithms/conversions/UnitConversions.java b/src/main/java/com/thealgorithms/conversions/UnitConversions.java
index 15f74a21a17e..8cbc2bf46610 100644
--- a/src/main/java/com/thealgorithms/conversions/UnitConversions.java
+++ b/src/main/java/com/thealgorithms/conversions/UnitConversions.java
@@ -3,49 +3,75 @@
import static java.util.Map.entry;
import java.util.Map;
-import org.apache.commons.lang3.tuple.Pair;
/**
* A utility class to perform unit conversions between different measurement systems.
- *
- * Currently, the class supports temperature conversions between several scales:
- * Celsius, Fahrenheit, Kelvin, Réaumur, Delisle, and Rankine.
- *
- * This class makes use of an {@link UnitsConverter} that handles the conversion logic
- * based on predefined affine transformations. These transformations include scaling factors
- * and offsets for temperature conversions.
- *
- * The {@code UnitsConverter} allows converting values between different units using
- * pre-defined affine conversion formulas. Each conversion is represented by an
- * {@link AffineConverter} that defines the scaling and offset for the conversion.
- *
- * For each unit, both direct conversions (e.g., Celsius to Fahrenheit) and inverse
- * conversions (e.g., Fahrenheit to Celsius) are generated automatically. It also computes
- * transitive conversions (e.g., Celsius to Kelvin via Fahrenheit if both conversions exist).
- *
- * Key features include:
- * Accepts a map of basic conversions and automatically generates inverse and
- * transitive conversions.
- *
- * @param basicConversions the initial set of unit conversions to add.
- */
- public UnitsConverter(final Map
* For more information, refer to:
* MRU on Wikipedia.
*
diff --git a/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java b/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java
index 1821872be9cd..bb88f3c954ba 100644
--- a/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java
+++ b/src/main/java/com/thealgorithms/datastructures/caches/RRCache.java
@@ -53,8 +53,8 @@ public final class RRCache
* The implementation leverages DFS to attempt to color the graph using two colors. If we can color the graph such
* that no two adjacent vertices have the same color, the graph is bipartite.
- *
+ *
* Example:
* Input (Adjacency Matrix):
* {{0, 1, 0, 1},
* {1, 0, 1, 0},
* {0, 1, 0, 1},
* {1, 0, 1, 0}}
- *
+ *
* Output: YES (This graph is bipartite)
- *
+ *
* Input (Adjacency Matrix):
* {{0, 1, 1, 0},
* {1, 0, 1, 0},
* {1, 1, 0, 1},
* {0, 0, 1, 0}}
- *
+ *
* Output: NO (This graph is not bipartite)
*/
public final class BipartiteGraphDFS {
@@ -34,7 +34,7 @@ private BipartiteGraphDFS() {
/**
* Helper method to perform DFS and check if the graph is bipartite.
- *
+ *
* During DFS traversal, this method attempts to color each vertex in such a way
* that no two adjacent vertices share the same color.
*
@@ -44,14 +44,14 @@ private BipartiteGraphDFS() {
* @param node Current vertex being processed
* @return True if the graph (or component of the graph) is bipartite, otherwise false
*/
- private static boolean bipartite(int v, ArrayList
* It uses a bucket queue (implemented here as a List of HashSets) to store vertices,
* where each bucket corresponds to a specific distance from the source. This is more
* efficient than a standard priority queue when the range of edge weights is small.
- *
+ *
* Time Complexity: O(E + W * V), where E is the number of edges, V is the number
* of vertices, and W is the maximum weight of any edge.
*
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java
index 70699a9461f7..4c94929d8bff 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java
@@ -20,7 +20,7 @@ public DijkstraAlgorithm(int vertexCount) {
/**
* Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices.
- *
+ *
* The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i}
* to vertex {@code j}. A value of 0 indicates no edge exists between the vertices.
*
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java
index a686b808a970..8b5ba00834b0 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java
@@ -23,7 +23,7 @@ public DijkstraOptimizedAlgorithm(int vertexCount) {
/**
* Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices.
- *
+ *
* The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i}
* to vertex {@code j}. A value of 0 indicates no edge exists between the vertices.
*
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java
index db716580d689..76ece5045f11 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java
@@ -215,12 +215,12 @@ private static void contractBlossom(BlossomData blossomData) {
* Auxiliary data class to encapsulate common parameters for the blossom operations.
*/
static class BlossomAuxData {
- Queue
* Johnson's algorithm works by using the Bellman-Ford algorithm to compute a transformation of the
* input graph that removes all negative weights, allowing Dijkstra's algorithm to be used for
* efficient shortest path computations.
- *
+ *
* Time Complexity: O(V^2 * log(V) + V*E)
* Space Complexity: O(V^2)
- *
+ *
* Where V is the number of vertices and E is the number of edges in the graph.
- *
- * For more information, please visit {@link https://en.wikipedia.org/wiki/Johnson%27s_algorithm}
+ /**
+ * For more information, please visit Johnson's Algorithm
*/
public final class JohnsonsAlgorithm {
diff --git a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
index 9a97bc3f4808..eb7e353120c0 100644
--- a/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
+++ b/src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
@@ -17,7 +17,7 @@
*/
class AdjacencyList
* For more information on cuckoo hashing, refer to
* this Wikipedia page.
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
index 5760d39f1df7..ade05d4075e8 100644
--- a/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
+++ b/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java
@@ -40,7 +40,7 @@ private Intersection() {
/**
* Computes the intersection of two integer arrays, preserving element frequency.
* For example, given [1,2,2,3] and [2,2,4], the result will be [2,2].
- *
+ *
* Steps:
* 1. Count the occurrences of each element in the first array using a map.
* 2. Iterate over the second array and collect common elements.
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
index 834de9c77881..79c6ad75c28a 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java
@@ -196,8 +196,7 @@ public void delete(HeapNode x) {
* @pre heap contains x
*/
private void decreaseKey(HeapNode x, int delta) {
- int newKey = x.getKey() - delta;
- x.key = newKey;
+ x.key = x.getKey() - delta;
if (x.isRoot()) { // no parent to x
this.updateMin(x);
return;
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java
index ad7229760fd0..5a1db5b14971 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java
@@ -5,7 +5,7 @@
import java.util.IdentityHashMap;
import java.util.Objects;
import java.util.function.Consumer;
-
+import java.util.HashMap;
/**
* An addressable (indexed) min-priority queue with O(log n) updates.
*
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java
index 7ad92e8ba3c1..5e34a141fe50 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java
@@ -17,7 +17,7 @@ private KthElementFinder() {
/**
* Finds the Kth largest element in the given array.
* Uses a min-heap of size K to track the largest K elements.
- *
+ *
* Time Complexity: O(n * log(k)), where n is the size of the input array.
* Space Complexity: O(k), as we maintain a heap of size K.
*
@@ -33,13 +33,13 @@ public static int findKthLargest(int[] nums, int k) {
minHeap.poll();
}
}
- return minHeap.peek();
+ return minHeap.element();
}
/**
* Finds the Kth smallest element in the given array.
* Uses a max-heap of size K to track the smallest K elements.
- *
+ *
* Time Complexity: O(n * log(k)), where n is the size of the input array.
* Space Complexity: O(k), as we maintain a heap of size K.
*
@@ -55,6 +55,6 @@ public static int findKthSmallest(int[] nums, int k) {
maxHeap.poll();
}
}
- return maxHeap.peek();
+ return maxHeap.element();
}
}
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
index 5b4b29cf1c2d..ffac21e8ec6f 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java
@@ -7,12 +7,12 @@
* A Max Heap implementation where each node's key is higher than or equal to its children's keys.
* This data structure provides O(log n) time complexity for insertion and deletion operations,
* and O(1) for retrieving the maximum element.
- *
+ *
* Properties:
* 1. Complete Binary Tree
* 2. Parent node's key ≥ Children nodes' keys
* 3. Root contains the maximum element
- *
+ *
* Example usage:
*
* Time Complexity:
* - Adding a number: O(log n) due to heap insertion.
* - Finding the median: O(1).
- *
+ *
* Space Complexity: O(n), where n is the total number of elements added.
*
* @author Hardvan
*/
public final class MedianFinder {
+
MedianFinder() {
}
- private PriorityQueue
* Time Complexity: O(n * log k), where n is the total number of elements across all arrays
* and k is the number of arrays.
- *
+ *
* Space Complexity: O(k) for the heap, where k is the number of arrays.
*
* @author Hardvan
diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
index 3a4822142b5f..3ab849aee953 100644
--- a/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
+++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java
@@ -7,12 +7,12 @@
* A Min Heap implementation where each node's key is lower than or equal to its children's keys.
* This data structure provides O(log n) time complexity for insertion and deletion operations,
* and O(1) for retrieving the minimum element.
- *
+ *
* Properties:
* 1. Complete Binary Tree
* 2. Parent node's key ≤ Children nodes' keys
* 3. Root contains the minimum element
- *
+ *
* Example usage:
* ```java
* List This implementation includes basic operations such as appending elements
* to the end, removing elements from a specified position, and converting
* the list to a string representation.
- *
* @param
* This implementation includes basic operations such as appending elements to
* the end,
* removing elements from a specified position, and converting the list to a
@@ -18,7 +18,7 @@ public class CircularDoublyLinkedList
* In this specific problem structure, each node has a `next` pointer (to the
* next node at the same level) and a `child` pointer (which points to the head
* of another sorted linked list). The goal is to merge all these lists into a
* single, vertically sorted linked list using the `child` pointer.
- *
+ *
* The approach is a recursive one that leverages a merge utility, similar to
* the merge step in Merge Sort. It recursively flattens the list starting from
* the rightmost node and merges each node's child list with the already
@@ -25,7 +25,7 @@ private FlattenMultilevelLinkedList() {
* reference to the head of a child list.
*/
static class Node {
- int data;
+ final int data;
Node next;
Node child;
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
index 0f5c50530d92..983d57c73381 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java
@@ -23,7 +23,7 @@
*
* This class is designed to handle nodes of integer linked lists and can be expanded for additional data types if needed. This implementation assumes the input lists are already sorted in ascending order. This method does not modify the input list. Reference: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare Reference: ...'s_tortoise_and_hare Complexity:
* Further information can be found here:
- * https://runestone.academy/ns/books/published/cppds/LinearLinked/ImplementinganOrderedList.html
+ * ...
*
- * Additional contributions made by: PuneetTri(https://github.com/PuneetTri)
+ * Additional contributions made by: PuneetTri(...)
*/
class PriorityQueue {
/**
* The max size of the queue
*/
- private int maxSize;
+ private final int maxSize;
/**
* The array for the queue
*/
- private int[] queueArray;
+ private final int[] queueArray;
/**
* How many items are in the queue
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/queues/Queue.java b/src/main/java/com/thealgorithms/datastructures/queues/Queue.java
index 046b79a020ed..0ab41d497a67 100644
--- a/src/main/java/com/thealgorithms/datastructures/queues/Queue.java
+++ b/src/main/java/com/thealgorithms/datastructures/queues/Queue.java
@@ -4,7 +4,7 @@
* This class implements a Queue data structure using an array.
* A queue is a first-in-first-out (FIFO) data structure where elements are
* added to the rear and removed from the front.
- *
+ *
* Note: This implementation is not thread-safe.
*/
public final class Queue
* Applications: Computer networks, API rate limiting, distributed systems, etc.
*
* @author Hardvan
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
index bbcdfe1cc2a8..66c68f0b09e0 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java
@@ -17,7 +17,7 @@ public class NodeStack This method is a helper for {@link #reverseStack(Stack)}.
- *
+ *
* Steps:
* 1. If the stack is empty, push the element and return.
* 2. Remove the top element from the stack.
diff --git a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
index c12097dfa28c..4cb3889c66c5 100644
--- a/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
+++ b/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java
@@ -17,7 +17,7 @@ private StackOfLinkedList() {
// A node class for the linked list
class Node {
- public int data;
+ public final int data;
public Node next;
Node(int data) {
@@ -78,7 +78,7 @@ public int pop() {
Node destroy = head;
head = head.next;
int retValue = destroy.data;
- destroy = null; // Help garbage collection
+ // Help garbage collection
size--;
return retValue;
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
index 07fc5c87b6c4..ba87106f0ca1 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
@@ -30,7 +30,7 @@ public class AVLSimple {
private class Node {
- int data;
+ final int data;
int height;
Node left;
Node right;
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
index 77ee5d5fa23e..27509ee1a16b 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
@@ -77,7 +77,7 @@ public void delete(int delKey) {
}
// Find the node to be deleted
- Node node = root;
+ Node node;
Node child = root;
while (child != null) {
node = child;
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
index 1962eaa0a106..a130ee019fff 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
@@ -4,7 +4,7 @@
/**
* Given a sorted array. Create a balanced binary search tree from it.
- *
+ *
* Steps: 1. Find the middle element of array. This will act as root 2. Use the
* left half recursively to create left subtree 3. Use the right half
* recursively to create right subtree
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
index 2c94224ddeb4..0538474a5404 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
@@ -8,7 +8,6 @@
*
*
* A recursive implementation of generic type BST.
- *
* Reference: Wiki links for BST
*
* Utility class to convert a {@link BinaryTree} into its string representation.
*
* The conversion follows a preorder traversal pattern (root → left → right)
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
index fff84111663b..28adb5fa1fca 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
@@ -5,20 +5,20 @@
/**
* Problem Statement Ceil value for any number x in a collection is a number y
* which is either equal to x or the least greater number than x.
- *
+ *
* Problem: Given a binary search tree containing positive integer values. Find
* ceil value for a given key in O(lg(n)) time. In case if it is not present
* return -1.
- *
+ *
* Ex.1. [30,20,40,10,25,35,50] represents level order traversal of a binary
* search tree. Find ceil for 10. Answer: 20
- *
+ *
* Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary
* search tree. Find ceil for 22 Answer: 25
- *
+ *
* Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary
* search tree. Find ceil for 52 Answer: -1
- *
+ *
* Solution 1: Brute Force Solution: Do an inorder traversal and save result
* into an array. Iterate over the array to get an element equal to or greater
* than current key. Time Complexity: O(n) Space Complexity: O(n) for auxiliary
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java b/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java
index 0b29dd6f5f5e..1f39b8cd1358 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java
@@ -37,7 +37,7 @@ public static final class CentroidTree {
private final int[] parent;
private final int[] subtreeSize;
private final boolean[] removed;
- private int root;
+ private final int root;
/**
* Constructs a centroid tree from an adjacency list.
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
index 17d84bf11d54..4f74c18683cd 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
@@ -11,7 +11,7 @@
* 2 2
* / \ / \
* 3 4 4 3
- *
+ *
* Below is not symmetric because values is different in last level
* 1
* / \
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
index 5378a01f6642..2b545721c5de 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
@@ -2,8 +2,8 @@
public class FenwickTree {
- private int n;
- private int[] fenTree;
+ private final int n;
+ private final int[] fenTree;
/* Constructor which takes the size of the array as a parameter */
public FenwickTree(int n) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
index 7d969a59def0..b644b51aa2fd 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
@@ -19,7 +19,7 @@ public class GenericTree {
private static final class Node {
int data;
- ArrayList
* Complexities:
* Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree.
- *
+ *
* Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree
* and 'h' is the height of a binary tree.
* In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance:
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
index 5190e82f74ef..1c6f697fd7e1 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
@@ -68,7 +68,7 @@ public class KDTree {
static class Point {
- int[] coordinates;
+ final int[] coordinates;
public int getCoordinate(int i) {
return coordinates[i];
@@ -142,7 +142,7 @@ public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) {
static class Node {
private Point point;
- private int axis; // 0 for x, 1 for y, 2 for z, etc.
+ private final int axis; // 0 for x, 1 for y, 2 for z, etc.
private Node left = null; // Left child
private Node right = null; // Right child
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
index 3aceac4d1852..46f82a233a11 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
@@ -8,10 +8,10 @@
/**
* Given tree is traversed in a 'pre-order' way: ROOT -> LEFT -> RIGHT.
* Below are given the recursive and iterative implementations.
- *
+ *
* Complexities:
* Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree.
- *
+ *
* Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree
* and 'h' is the height of a binary tree.
* In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance:
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java
index 3ef664f3fa7d..e2d51e892d15 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java
@@ -9,7 +9,7 @@ class TreeNode {
// Members
- int key;
+ final int key;
TreeNode left;
TreeNode right;
@@ -26,8 +26,8 @@ class TreeNode {
// distance of node from root
class QItem {
- TreeNode node;
- int hd;
+ final TreeNode node;
+ final int hd;
QItem(TreeNode n, int h) {
node = n;
@@ -38,7 +38,7 @@ class QItem {
// Class for a Binary Tree
class Tree {
- TreeNode root;
+ final TreeNode root;
// Constructors
Tree() {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java
index e0d255b1e784..e55d4e238243 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java
@@ -10,8 +10,8 @@
* @author Sailok Chinta
*/
class Point {
- public double x;
- public double y;
+ public final double x;
+ public final double y;
Point(double x, double y) {
this.x = x;
@@ -26,8 +26,8 @@ class Point {
* @author Sailok Chinta
*/
class BoundingBox {
- public Point center;
- public double halfWidth;
+ public final Point center;
+ public final double halfWidth;
BoundingBox(Point center, double halfWidth) {
this.center = center;
@@ -59,7 +59,7 @@ public boolean intersectsBoundingBox(BoundingBox otherBoundingBox) {
/**
* QuadTree is a tree data structure that is used to store spatial information
* in an efficient way.
- *
+ *
* This implementation is specific to Point QuadTrees
*
* @see Quad Tree
@@ -69,7 +69,7 @@ public class QuadTree {
private final BoundingBox boundary;
private final int capacity;
- private List
* Time Complexity:
* - Build/Initialization: O(N * M)
* - Point Update: O(log N * log M)
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java
index 2668b609aedc..585f18068887 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java
@@ -1,33 +1,22 @@
package com.thealgorithms.datastructures.trees;
+import java.io.Serial;
import java.util.LinkedList;
import java.util.List;
/**
* Implementation of a Splay Tree data structure.
- *
- * A splay tree is a self-adjusting binary search tree with the additional
- * property
+ *
+ * A splay tree is a self-adjusting binary search tree with the additional property
* that recently accessed elements are quick to access again. It performs basic
- * operations such as insertion, deletion, and searching in O(log n) amortized
- * time,
- * where n is the number of elements in the tree.
- *
- * The key feature of splay trees is the splay operation, which moves a node
- * closer
- * to the root of the tree when it is accessed. This operation helps to maintain
- * good balance and improves the overall performance of the tree. After
- * performing
- * a splay operation, the accessed node becomes the new root of the tree.
- *
- * Splay trees have applications in various areas, including caching, network
- * routing,
- * and dynamic optimality analysis.
+ * operations such as insertion, deletion, and searching in O(log n) amortized time.
*/
public class SplayTree {
- public static final TreeTraversal PRE_ORDER = new PreOrderTraversal();
- public static final TreeTraversal IN_ORDER = new InOrderTraversal();
- public static final TreeTraversal POST_ORDER = new PostOrderTraversal();
+
+ // Preserved public API constants
+ public static final TreeTraversal PRE_ORDER = TraversalStrategy.PRE_ORDER;
+ public static final TreeTraversal IN_ORDER = TraversalStrategy.IN_ORDER;
+ public static final TreeTraversal POST_ORDER = TraversalStrategy.POST_ORDER;
private Node root;
@@ -57,15 +46,18 @@ public void insert(final int key) {
* @return True if the key is found, otherwise false.
*/
public boolean search(int key) {
+ if (isEmpty()) {
+ return false;
+ }
root = splay(root, key);
- return root != null && root.key == key;
+ return root.key == key;
}
/**
* Deletes a key from the SplayTree.
*
* @param key The key to delete.
- * @throws IllegalArgumentException If the tree is empty.
+ * @throws EmptyTreeException If the tree is empty.
*/
public void delete(final int key) {
if (isEmpty()) {
@@ -81,9 +73,9 @@ public void delete(final int key) {
if (root.left == null) {
root = root.right;
} else {
- Node temp = root;
+ Node rightSubtree = root.right;
root = splay(root.left, findMax(root.left).key);
- root.right = temp.right;
+ root.right = rightSubtree;
}
}
@@ -95,171 +87,96 @@ public void delete(final int key) {
*/
public List
- * This method traverses the right children of the subtree until it finds the
- * rightmost node, which contains the maximum key.
- *
- * The zig operation is used to perform a single rotation on a node to move it
- * closer to
- * the root of the tree. It is typically applied when the node is a left child
- * of its parent
- * and needs to be rotated to the right.
- *
- * The zag operation is used to perform a single rotation on a node to move it
- * closer to
- * the root of the tree. It is typically applied when the node is a right child
- * of its parent
- * and needs to be rotated to the left.
- *
- * The splay operation is the core operation of a splay tree. It moves a
- * specified node
- * closer to the root of the tree by performing a series of rotations. The goal
- * of the splay
- * operation is to improve the access time for frequently accessed nodes by
- * bringing them
- * closer to the root.
- *
- * The splay operation consists of three main cases:
- *
- * After performing the splay operation, the accessed node becomes the new root
- * of the tree.
- *
* value -> holds the value of the node.
* Binary Search Tree is built based on value.
- *
+ *
* priority -> holds the priority of the node.
* Heaps are maintained based on priority.
* It is randomly assigned
- *
+ *
* size -> holds the size of the subtree with current node as root
- *
+ *
* left -> holds the left subtree
* right -> holds the right subtree
*/
- public int value;
- private int priority;
+ public final int value;
+ private final int priority;
private int size;
public TreapNode left;
public TreapNode right;
@@ -61,11 +61,11 @@ private void updateSize() {
* random -> to generate random priority for the nodes in the Treap
*/
private TreapNode root;
- private Random random = new Random();
+ private final Random random = new Random();
/**
* Constructors
- *
+ *
* Treap() -> create an empty Treap
* Treap(int[] nodeValues) -> add the elements given in the array to the Treap
*/
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
index cf56731fb079..7b35a8c68238 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
@@ -34,9 +34,9 @@ private final class Node {
}
// Using an arraylist to store the inorder traversal of the given binary tree
- static ArrayList
* All known subclasses: {@link TreeNode}, {@link SimpleNode}.
*
* @param
* All known subclasses: {@link SimpleTreeNode}, {@link LargeTreeNode}.
*
* @param
* The task is to determine whether it is possible to make string `a` equal to string `b`.
*
* @author Hardvan
@@ -24,7 +24,7 @@ private Abbreviation() {
* @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.
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java b/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java
index e7712b13a2b7..b7b2be19f2d4 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/AllConstruct.java
@@ -5,7 +5,7 @@
/**
* 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.
@@ -21,7 +21,7 @@ private AllConstruct() {
* 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.
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
index ccd54ee4349a..57a65989d338 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/BoundaryFill.java
@@ -2,7 +2,7 @@
/**
* Java program for Boundary fill algorithm.
- * @author Akshay Dubey (https://github.com/itsAkshayDubey)
+ * @author Akshay Dubey (...)
*/
public final class BoundaryFill {
private BoundaryFill() {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
index d01066f611bd..b2a78b94ceb2 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CatalanNumber.java
@@ -4,7 +4,7 @@
/**
* This file contains an implementation of finding the nth CATALAN NUMBER using
* dynamic programming : Wikipedia
- *
+ *
* Time Complexity: O(n^2) Space Complexity: O(n)
*
* @author AMRITESH ANAND
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
index 7edc9603dc8b..6c8c7378ad1e 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/CoinChange.java
@@ -1,7 +1,7 @@
package com.thealgorithms.dynamicprogramming;
/**
- * @author Varun Upadhyay (https://github.com/varunu28)
+ * @author Varun Upadhyay (...)
*/
public final class CoinChange {
private CoinChange() {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java
index 9721d4ab0ad5..ba7520fb1078 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DamerauLevenshteinDistance.java
@@ -5,14 +5,14 @@
/**
* 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)
*/
@@ -60,7 +60,7 @@ private static void validateInputs(String s1, String s2) {
/**
* 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.
*
@@ -81,11 +81,11 @@ private static Map
* 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.
@@ -116,11 +116,11 @@ private static int[][] initializeTable(int n, int m) {
/**
* 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.
*
@@ -156,13 +156,13 @@ private static void fillTable(String s1, String s2, int[][] dp, Map
* The transposition cost accounts for the gap between the current position
* and the last position where matching characters were found.
*
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java b/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java
index 7dae7603fedc..f549bf4f2ee6 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/DigitDP.java
@@ -61,7 +61,7 @@ private static long countWithDigitSum(long number, int target) {
/**
* Recursive memoized function to explore digit placements.
- *
+ *
* Time Complexity: O(number_of_digits * target_sum * 10)
* Space Complexity: O(number_of_digits * target_sum * 2)
*
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
index 0d6aff2bbef3..045d62b42b19 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Fibonacci.java
@@ -4,7 +4,7 @@
import java.util.Map;
/**
- * @author Varun Upadhyay (https://github.com/varunu28)
+ * @author Varun Upadhyay (...)
*/
public final class Fibonacci {
private Fibonacci() {
@@ -76,7 +76,7 @@ public static int fibBotUp(int n) {
*
* Whereas , the above functions will take O(n) Space.
* @throws IllegalArgumentException if n is negative
- * @author Shoaib Rayeen (https://github.com/shoaibrayeen)
+ * @author Shoaib Rayeen (...)
*/
public static int fibOptimized(int n) {
if (n < 0) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
index 7a0a3da94c1e..8cef4bfa36ae 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KadaneAlgorithm.java
@@ -4,7 +4,7 @@
* 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: Siddhant Swarup Mallick
*/
public final class KadaneAlgorithm {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
index 0d4c8d501f9f..5ca5714f809f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Knapsack.java
@@ -4,14 +4,11 @@
/**
* 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}
@@ -64,7 +61,7 @@ public static int knapSack(final int weightCapacity, final int[] weights, final
return dp[weightCapacity];
}
- /*
+
// Example main method for local testing only.
public static void main(String[] args) {
int[] values = {60, 100, 120};
@@ -74,5 +71,5 @@ public static void main(String[] args) {
int maxValue = knapSack(weightCapacity, weights, values);
System.out.println("Maximum value = " + maxValue); // Output: 220
}
- */
+
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java
index abc1e321ca8f..cee0edb9bac5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOne.java
@@ -4,11 +4,11 @@
* 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
+ *
+ * Problem Refhttps://en.wikipedia.org/wiki/Knapsack_problem
*/
public final class KnapsackZeroOne {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java
index c560efc61c71..62b5ad53618f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/KnapsackZeroOneTabulation.java
@@ -5,18 +5,18 @@
* 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
+ *
+ * For more informatisee:
+ * https://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming
*/
public final class KnapsackZeroOneTabulation {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
index 119d65dfe365..41c82d37c827 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LevenshteinDistance.java
@@ -4,7 +4,7 @@
/**
* 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.
*/
@@ -14,19 +14,19 @@ 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.
*/
@@ -43,18 +43,18 @@ public static int naiveLevenshteinDistance(final String string1, final String st
/**
* 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.
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java
index ba1def551192..d55af13c89e5 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestArithmeticSubsequence.java
@@ -9,7 +9,7 @@ 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).
*
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
index 54837b5f4e71..d123c65321e7 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestCommonSubsequence.java
@@ -5,7 +5,7 @@
* 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 {
@@ -26,7 +26,7 @@ public static String getLCS(String str1, String str2) {
return null;
}
// If either string is empty, return an empty string as LCS.
- if (str1.length() == 0 || str2.length() == 0) {
+ if (str1.isEmpty() || str2.isEmpty()) {
return "";
}
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
index 470833ce9c97..b08b858da67f 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequence.java
@@ -1,7 +1,7 @@
package com.thealgorithms.dynamicprogramming;
/**
- * @author Afrizal Fikri (https://github.com/icalF)
+ * @author Afrizal Fikri (...)
*/
public final class LongestIncreasingSubsequence {
private LongestIncreasingSubsequence() {
@@ -53,7 +53,7 @@ else if (array[i] > tail[length - 1]) {
}
/**
- * @author Alon Firestein (https://github.com/alonfirestein)
+ * @author Alon Firestein (...)
*/
// A function for finding the length of the LIS algorithm in O(nlogn) complexity.
public static int findLISLen(int[] a) {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java
index 7bc0855e0566..47e70b6adb6b 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestIncreasingSubsequenceNLogN.java
@@ -4,7 +4,7 @@
* 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)
+ * @author Vusal Huseynov (...)
*/
public final class LongestIncreasingSubsequenceNLogN {
private LongestIncreasingSubsequenceNLogN() {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
index 02696bfca9c2..e717cc674a86 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/LongestValidParentheses.java
@@ -4,7 +4,7 @@
* 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)
+ * @author Libin Yang (...)
* @since 2018/10/5
*/
public final class LongestValidParentheses {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
index 49af3ae3db88..1118b494c533 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/MaximumSumOfNonAdjacentElements.java
@@ -4,7 +4,7 @@
* 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 {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java b/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java
index 13b640cf0d04..7247ebe7cca7 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/NeedlemanWunsch.java
@@ -4,7 +4,7 @@
* 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)
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java
index 428176ea6c40..6064e1e2c49c 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalBinarySearchTree.java
@@ -13,7 +13,7 @@
* and 10 as its left child. The total cost is 50 * 1 + 34 * 2 = 118.
*
* Reference:
- * https://en.wikipedia.org/wiki/Optimal_binary_search_tree
+ * ...
*/
public final class OptimalBinarySearchTree {
private OptimalBinarySearchTree() {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
index e31bb73096e8..bc347350f55e 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/OptimalJobScheduling.java
@@ -4,8 +4,8 @@
* 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
+ * * https://en.wikipedia.org/wiki/Optimal_job_scheduling
*
* @author georgioct@csd.auth.gr
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
index 8c72fa347f50..ef3ab5d508c2 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/PartitionProblem.java
@@ -2,11 +2,11 @@
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.
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
index 181ac72a654d..97262eb73792 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/RegexMatching.java
@@ -5,11 +5,11 @@
* 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
+ *
+ * Memoization vs Tabul: https://www.geeksforgeeks.org/tabulation-vs-memoization/
+ * Question...tching/1
*/
public final class RegexMatching {
private RegexMatching() {
@@ -19,7 +19,7 @@ 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.
*
@@ -28,13 +28,13 @@ private RegexMatching() {
* @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) {
+ if (src.isEmpty() && pat.isEmpty()) {
return true;
}
- if (src.length() != 0 && pat.length() == 0) {
+ if (!src.isEmpty() && pat.isEmpty()) {
return false;
}
- if (src.length() == 0 && pat.length() != 0) {
+ if (src.isEmpty() && !pat.isEmpty()) {
for (int i = 0; i < pat.length(); i++) {
if (pat.charAt(i) != '*') {
return false;
@@ -64,7 +64,7 @@ public static boolean regexRecursion(String src, String pat) {
/**
* 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.
*
@@ -108,7 +108,7 @@ static boolean regexRecursion(String src, String pat, int svidx, int pvidx) {
/**
* 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.
*
@@ -158,7 +158,7 @@ public static boolean regexRecursion(String src, String pat, int svidx, int pvid
* 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.
*
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java b/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java
index c0d66f68b502..69ca7e42dddd 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SmithWaterman.java
@@ -3,7 +3,7 @@
/**
* 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)
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java
index e9c15c1b4f24..478d711c3036 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/SumOfSubset.java
@@ -3,11 +3,11 @@
/**
* 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
+ *
+ * Wikhttps://en.wikipedia.org/wiki/Subset_sum_problem
*/
public final class SumOfSubset {
@@ -22,7 +22,7 @@ private SumOfSubset() {
* @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
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java b/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java
index 9fd82ccaf078..4448b6ed8a72 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/TreeMatching.java
@@ -5,7 +5,7 @@
/**
* 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
@@ -16,8 +16,8 @@
*/
public class TreeMatching {
- private UndirectedAdjacencyListGraph graph;
- private int[][] dp;
+ private final UndirectedAdjacencyListGraph graph;
+ private final int[][] dp;
/**
* Constructor that initializes the graph and the DP table.
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
index 3ff6cc620236..71b3e69bb2ba 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/Tribonacci.java
@@ -2,7 +2,7 @@
/**
* 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/
+ * N-th Tribonacci Number - ...
*/
public final class Tribonacci {
private Tribonacci() {
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
index 22ad8a7dd8e3..197e2a5d5a13 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniquePaths.java
@@ -4,7 +4,7 @@
/**
* Author: Siddhant Swarup Mallick
- * Github: https://github.com/siddhant2002
+ * Github: ...
*
* Problem Description:
* A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
index 8c7ea6179e3f..a13725532812 100755
--- a/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/UniqueSubsequencesCount.java
@@ -12,7 +12,7 @@
* using dynamic programming and recursion. It ensures that duplicate characters
* are not counted multiple times in the subsequences. Author: https://github.com/Tuhinm2002 Author: ...
* Use DP to return True if the pattern matches the entire text and False otherwise
*
*/
diff --git a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
index 022b43184a88..72ddc2a9f2b3 100644
--- a/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
+++ b/src/main/java/com/thealgorithms/dynamicprogramming/WineProblem.java
@@ -5,19 +5,19 @@
* 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)
diff --git a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java
index 51d9930c0250..540aae90c873 100644
--- a/src/main/java/com/thealgorithms/geometry/BresenhamLine.java
+++ b/src/main/java/com/thealgorithms/geometry/BresenhamLine.java
@@ -11,8 +11,8 @@
*
* This algorithm uses integer arithmetic to calculate the points,
* making it suitable for rasterization in computer graphics. All methods are stateless and side-effect-free.
+ * No algorithm control-flow lives here — only geometry. For collinear points the method returns {@code true} when {@code k} falls
+ * between {@code i} and {@code j} (inclusive), so that segment endpoints are
+ * treated as hull candidates. Using squared distance avoids floating-point arithmetic while still
+ * providing a consistent total order on distances. Intermediate collinear points are removed so that only the farthest
+ * point along each ray from the pivot is retained. Any class implementing this interface accepts a list of {@link Point}s
+ * and returns the hull vertices in counter-clockwise order. For every pair of points {@code (i, j)}, the algorithm checks whether all
+ * remaining points lie on the same side of the directed line {@code i→j}.
+ * If they do, both endpoints are hull vertices. The algorithm splits the point set into an upper and a lower hull relative
+ * to the line connecting the leftmost and rightmost points, then recursively
+ * finds the extreme point of each sub-hull. Returns points in counter-clockwise order starting from the bottom-most,
+ * left-most point.> nm = new ArrayList<>();
+ static final List
> nm = new ArrayList<>();
// adjacency list
private ArrayList
* int decimal = BcdConversion.bcdToDecimal(0x1234);
diff --git a/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java
index 3e9a4a21183f..9ecf1eda1e6d 100644
--- a/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java
+++ b/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java
@@ -3,7 +3,7 @@
/**
* ClearLeftmostSetBit class contains a method to clear the leftmost set bit of a number.
* The leftmost set bit is the leftmost bit that is set to 1 in the binary representation of a number.
- *
+ *
* int binary = Xs3Conversion.xs3ToBinary(0x4567);
diff --git a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
index 979f18532eaa..c12907088ee2 100644
--- a/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/AffineCipher.java
@@ -3,10 +3,10 @@
/**
* The AffineCipher class implements the Affine cipher, a type of monoalphabetic substitution cipher.
* It encrypts and decrypts messages using a linear transformation defined by the formula:
- *
+ *
* RSA rsa = new RSA(1024);
diff --git a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
index f81252980468..596c414b79b4 100644
--- a/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/RailFenceCipher.java
@@ -5,8 +5,8 @@
/**
* The rail fence cipher (also called a zigzag cipher) is a classical type of transposition cipher.
* It derives its name from the manner in which encryption is performed, in analogy to a fence built with horizontal rails.
- * https://en.wikipedia.org/wiki/Rail_fence_cipher
- * @author https://github.com/Krounosity
+ * ...
+ * @author ...
*/
public class RailFenceCipher {
diff --git a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
index f6c88ef730ec..b4edcf20ac50 100644
--- a/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
+++ b/src/main/java/com/thealgorithms/ciphers/SimpleSubCipher.java
@@ -15,8 +15,6 @@ public class SimpleSubCipher {
/**
* Encrypt text by replacing each element with its opposite character.
*
- * @param message
- * @param cipherSmall
* @return Encrypted message
*/
public String encode(String message, String cipherSmall) {
@@ -52,8 +50,6 @@ public String encode(String message, String cipherSmall) {
* Decrypt message by replacing each element with its opposite character in
* cipher.
*
- * @param encryptedMessage
- * @param cipherSmall
* @return message
*/
public String decode(String encryptedMessage, String cipherSmall) {
diff --git a/src/main/java/com/thealgorithms/ciphers/Vigenere.java b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
index 0f117853bb85..ad5ee18a3cd5 100644
--- a/src/main/java/com/thealgorithms/ciphers/Vigenere.java
+++ b/src/main/java/com/thealgorithms/ciphers/Vigenere.java
@@ -2,24 +2,24 @@
/**
* A Java implementation of the Vigenère Cipher.
- *
+ *
Example Usage
- *
- * double result = UnitConversions.TEMPERATURE.convert("Celsius", "Fahrenheit", 100.0);
- * // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C)
- *
- *
- * Temperature Scales Supported
- *
- *
*/
public final class UnitConversions {
- private UnitConversions() {
+
+ /**
+ * Enum managing supported temperature scales to eliminate magic strings
+ * and enforce structural type safety internally.
+ */
+ private enum TemperatureScale {
+ CELSIUS("Celsius"),
+ FAHRENHEIT("Fahrenheit"),
+ KELVIN("Kelvin"),
+ REAUMUR("Réaumur"),
+ DELISLE("Delisle"),
+ RANKINE("Rankine");
+
+ private final String unitName;
+
+ TemperatureScale(String unitName) {
+ this.unitName = unitName;
+ }
+
+ public String getName() {
+ return unitName;
+ }
}
+ // Mathematical Constants for Conversions (Eliminating Magic Numbers)
+ private static final double ABSOLUTE_ZERO_CELSIUS = -273.15;
+
+ private static final double CELSIUS_TO_FAHRENHEIT_SCALE = 9.0 / 5.0;
+ private static final double CELSIUS_TO_FAHRENHEIT_OFFSET = 32.0;
+
+ private static final double REAUMUR_TO_CELSIUS_SCALE = 5.0 / 4.0;
+
+ private static final double DELISLE_TO_CELSIUS_SCALE = -2.0 / 3.0;
+ private static final double DELISLE_TO_CELSIUS_OFFSET = 100.0;
+
+ private static final double RANKINE_TO_KELVIN_SCALE = 5.0 / 9.0;
+
/**
- * A preconfigured instance of {@link UnitsConverter} for temperature conversions.
- * The converter handles conversions between the following temperature units:
- *
- *
+ * Preconfigured instance of UnitsConverter for temperature conversions.
*/
- public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15)), entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)),
- entry(Pair.of("Réaumur", "Celsius"), new AffineConverter(5.0 / 4.0, 0.0)), entry(Pair.of("Delisle", "Celsius"), new AffineConverter(-2.0 / 3.0, 100.0)), entry(Pair.of("Rankine", "Kelvin"), new AffineConverter(5.0 / 9.0, 0.0))));
-}
+ public static final UnitsConverter TEMPERATURE = new UnitsConverter(Map.ofEntries(
+ entry(
+ new UnitPair(TemperatureScale.KELVIN.getName(), TemperatureScale.CELSIUS.getName()),
+ new AffineConverter(1.0, ABSOLUTE_ZERO_CELSIUS)
+ ),
+ entry(
+ new UnitPair(TemperatureScale.CELSIUS.getName(), TemperatureScale.FAHRENHEIT.getName()),
+ new AffineConverter(CELSIUS_TO_FAHRENHEIT_SCALE, CELSIUS_TO_FAHRENHEIT_OFFSET)
+ ),
+ entry(
+ new UnitPair(TemperatureScale.REAUMUR.getName(), TemperatureScale.CELSIUS.getName()),
+ new AffineConverter(REAUMUR_TO_CELSIUS_SCALE, 0.0)
+ ),
+ entry(
+ new UnitPair(TemperatureScale.DELISLE.getName(), TemperatureScale.CELSIUS.getName()),
+ new AffineConverter(DELISLE_TO_CELSIUS_SCALE, DELISLE_TO_CELSIUS_OFFSET)
+ ),
+ entry(
+ new UnitPair(TemperatureScale.RANKINE.getName(), TemperatureScale.KELVIN.getName()),
+ new AffineConverter(RANKINE_TO_KELVIN_SCALE, 0.0)
+ )
+ ));
+
+ private UnitConversions() {
+ // Prevent instantiation
+ }
+}
\ No newline at end of file
diff --git a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
index 00690b2c0f9b..c64053a81835 100644
--- a/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
+++ b/src/main/java/com/thealgorithms/conversions/UnitsConverter.java
@@ -4,144 +4,161 @@
import java.util.HashSet;
import java.util.Map;
import java.util.NoSuchElementException;
+import java.util.Objects;
import java.util.Set;
-import org.apache.commons.lang3.tuple.Pair;
/**
- * A class that handles unit conversions using affine transformations.
- *
- *
- *
- *
- * Example Usage
- *
- * Map<Pair<String, String>, AffineConverter> basicConversions = Map.ofEntries(
- * entry(Pair.of("Celsius", "Fahrenheit"), new AffineConverter(9.0 / 5.0, 32.0)),
- * entry(Pair.of("Kelvin", "Celsius"), new AffineConverter(1.0, -273.15))
- * );
- *
- * UnitsConverter converter = new UnitsConverter(basicConversions);
- * double result = converter.convert("Celsius", "Fahrenheit", 100.0);
- * // Output: 212.0 (Celsius to Fahrenheit conversion of 100°C)
- *
- *
- * Exception Handling
- *
- *
+ * Represents a directed conversion between two units using an affine transformation.
*/
-public final class UnitsConverter {
- private final Map
* List
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
index dac88dd9f241..1d3a2c056f24 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java
@@ -35,7 +35,7 @@ public class RandomNode {
static class ListNode {
- int val;
+ final int val;
ListNode next;
ListNode(int val) {
diff --git a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java
index 9b9464d388b5..51043229107a 100644
--- a/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java
+++ b/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java
@@ -28,7 +28,7 @@
*
* {
- S val;
+ final S val;
DequeNode next = null;
DequeNode prev = null;
@@ -59,12 +59,11 @@ public void addLast(T val) {
DequeNode> tree;
- private int[] parent;
- private int[] depth;
- private int[] subtreeSize;
- private int[] chainHead;
- private int[] position;
- private int[] nodeValue;
- private int[] segmentTree;
+ private final List
> tree;
+ private final int[] parent;
+ private final int[] depth;
+ private final int[] subtreeSize;
+ private final int[] chainHead;
+ private final int[] position;
+ private final int[] nodeValue;
+ private final int[] segmentTree;
private int positionIndex;
public HeavyLightDecomposition(int n) {
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
index 5a001ff9ab9f..f238047b6d37 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
@@ -8,10 +8,10 @@
/**
* Given tree is traversed in an 'inorder' way: LEFT -> ROOT -> RIGHT.
* Below are given the recursive and iterative implementations.
- *
+ *
- *
- * > traverse(BinaryTree.Node root) {
// traverse all the level nodes
for (int i = 0; i < nodesOnLevel; i++) {
BinaryTree.Node node = q.poll();
+ assert node != null;
if (prevLevelFromLeftToRight) {
- level.add(0, node.data);
+ level.addFirst(node.data);
} else {
level.add(node.data);
}
diff --git a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
index 6c53666e5856..f5559f990166 100644
--- a/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
+++ b/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
@@ -53,7 +53,7 @@ class NRKTree {
public NRKTree left;
public NRKTree right;
- public int data;
+ public final int data;
NRKTree(int x) {
this.left = null;
diff --git a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
index d69288f72200..5e186712e643 100644
--- a/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
+++ b/src/main/java/com/thealgorithms/devutils/nodes/LargeTreeNode.java
@@ -39,7 +39,7 @@ public LargeTreeNode(E data) {
*
* @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)
+ * @see TreeNode#TreeNode(Object, TreeNode)
*/
public LargeTreeNode(E data, LargeTreeNode
diff --git a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
index 0e8d9442138c..558b1bd2cb1b 100644
--- a/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
+++ b/src/main/java/com/thealgorithms/divideandconquer/SkylineAlgorithm.java
@@ -11,7 +11,7 @@
*/
public class SkylineAlgorithm {
- private ArrayList