repo stringclasses 1k values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 6 values | commit_sha stringclasses 1k values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java | src/main/java/com/thealgorithms/conversions/BinaryToHexadecimal.java | package com.thealgorithms.conversions;
import java.util.HashMap;
import java.util.Map;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*/
public final class BinaryToHexadecimal {
private static final int BITS_IN_HEX_DIGIT = 4;
private static final int BASE_BINARY = 2;
private static final int BASE_DECIMAL = 10;
private static final int HEX_START_DECIMAL = 10;
private static final int HEX_END_DECIMAL = 15;
private BinaryToHexadecimal() {
}
/**
* Converts a binary number to a hexadecimal number.
*
* @param binary The binary number to convert.
* @return The hexadecimal representation of the binary number.
* @throws IllegalArgumentException If the binary number contains digits other than 0 and 1.
*/
public static String binToHex(int binary) {
Map<Integer, String> hexMap = initializeHexMap();
StringBuilder hex = new StringBuilder();
while (binary != 0) {
int decimalValue = 0;
for (int i = 0; i < BITS_IN_HEX_DIGIT; i++) {
int currentBit = binary % BASE_DECIMAL;
if (currentBit > 1) {
throw new IllegalArgumentException("Incorrect binary digit: " + currentBit);
}
binary /= BASE_DECIMAL;
decimalValue += (int) (currentBit * Math.pow(BASE_BINARY, i));
}
hex.insert(0, hexMap.get(decimalValue));
}
return !hex.isEmpty() ? hex.toString() : "0";
}
/**
* Initializes the hexadecimal map with decimal to hexadecimal mappings.
*
* @return The initialized map containing mappings from decimal numbers to hexadecimal digits.
*/
private static Map<Integer, String> initializeHexMap() {
Map<Integer, String> hexMap = new HashMap<>();
for (int i = 0; i < BASE_DECIMAL; i++) {
hexMap.put(i, String.valueOf(i));
}
for (int i = HEX_START_DECIMAL; i <= HEX_END_DECIMAL; i++) {
hexMap.put(i, String.valueOf((char) ('A' + i - HEX_START_DECIMAL)));
}
return hexMap;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java | src/main/java/com/thealgorithms/bitmanipulation/OneBitDifference.java | package com.thealgorithms.bitmanipulation;
/**
* 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.
*
* @author Hardvan
*/
public final class OneBitDifference {
private OneBitDifference() {
}
/**
* Checks if two integers differ by exactly one bit.
*
* @param x the first integer
* @param y the second integer
* @return true if x and y differ by exactly one bit, false otherwise
*/
public static boolean differByOneBit(int x, int y) {
if (x == y) {
return false;
}
int xor = x ^ y;
return (xor & (xor - 1)) == 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGates.java | src/main/java/com/thealgorithms/bitmanipulation/BooleanAlgebraGates.java | package com.thealgorithms.bitmanipulation;
import java.util.List;
/**
* Implements various Boolean algebra gates (AND, OR, NOT, XOR, NAND, NOR)
*/
public final class BooleanAlgebraGates {
private BooleanAlgebraGates() {
// Prevent instantiation
}
/**
* Represents a Boolean gate that takes multiple inputs and returns a result.
*/
interface BooleanGate {
/**
* Evaluates the gate with the given inputs.
*
* @param inputs The input values for the gate.
* @return The result of the evaluation.
*/
boolean evaluate(List<Boolean> inputs);
}
/**
* AND Gate implementation.
* Returns true if all inputs are true; otherwise, false.
*/
static class ANDGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
for (boolean input : inputs) {
if (!input) {
return false;
}
}
return true;
}
}
/**
* OR Gate implementation.
* Returns true if at least one input is true; otherwise, false.
*/
static class ORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
for (boolean input : inputs) {
if (input) {
return true;
}
}
return false;
}
}
/**
* NOT Gate implementation (Unary operation).
* Negates a single input value.
*/
static class NOTGate {
/**
* Evaluates the negation of the input.
*
* @param input The input value to be negated.
* @return The negated value.
*/
public boolean evaluate(boolean input) {
return !input;
}
}
/**
* XOR Gate implementation.
* Returns true if an odd number of inputs are true; otherwise, false.
*/
static class XORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
boolean result = false;
for (boolean input : inputs) {
result ^= input;
}
return result;
}
}
/**
* NAND Gate implementation.
* Returns true if at least one input is false; otherwise, false.
*/
static class NANDGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
return !new ANDGate().evaluate(inputs); // Equivalent to negation of AND
}
}
/**
* NOR Gate implementation.
* Returns true if all inputs are false; otherwise, false.
*/
static class NORGate implements BooleanGate {
@Override
public boolean evaluate(List<Boolean> inputs) {
return !new ORGate().evaluate(inputs); // Equivalent to negation of OR
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/HammingDistance.java | src/main/java/com/thealgorithms/bitmanipulation/HammingDistance.java | package com.thealgorithms.bitmanipulation;
/**
* The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
* Given two integers x and y, calculate the Hamming distance.
* Example:
* Input: x = 1, y = 4
* Output: 2
* Explanation: 1 (0001) and 4 (0100) have 2 differing bits.
*
* @author Hardvan
*/
public final class HammingDistance {
private HammingDistance() {
}
/**
* Calculates the Hamming distance between two integers.
* The Hamming distance is the number of differing bits between the two integers.
*
* @param x The first integer.
* @param y The second integer.
* @return The Hamming distance (number of differing bits).
*/
public static int hammingDistance(int x, int y) {
int xor = x ^ y;
return Integer.bitCount(xor);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java | src/main/java/com/thealgorithms/bitmanipulation/ClearLeftmostSetBit.java | package com.thealgorithms.bitmanipulation;
/**
* 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.
*
* Example:
* 26 (11010) -> 10 (01010)
* 1 (1) -> 0 (0)
* 7 (111) -> 3 (011)
* 6 (0110) -> 2 (0010)
*
* @author Hardvan
*/
public final class ClearLeftmostSetBit {
private ClearLeftmostSetBit() {
}
/**
* Clears the leftmost set bit (1) of a given number.
* Step 1: Find the position of the leftmost set bit
* Step 2: Create a mask with all bits set except for the leftmost set bit
* Step 3: Clear the leftmost set bit using AND with the mask
*
* @param num The input number.
* @return The number after clearing the leftmost set bit.
*/
public static int clearLeftmostSetBit(int num) {
int pos = 0;
int temp = num;
while (temp > 0) {
temp >>= 1;
pos++;
}
int mask = ~(1 << (pos - 1));
return num & mask;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java | src/main/java/com/thealgorithms/bitmanipulation/HighestSetBit.java | package com.thealgorithms.bitmanipulation;
import java.util.Optional;
/**
* 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).
*
* @author Bama Charan Chhandogi
* @version 1.0
* @since 2021-06-23
*/
public final class HighestSetBit {
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}.
*
* @param num The input integer for which the highest set bit is to be found. It must be non-negative.
* @return An {@link Optional} containing the index of the highest set bit (zero-based).
* Returns {@link Optional#empty()} if the number is 0.
* @throws IllegalArgumentException if the input number is negative.
*/
public static Optional<Integer> findHighestSetBit(int num) {
if (num < 0) {
throw new IllegalArgumentException("Input cannot be negative");
}
if (num == 0) {
return Optional.empty();
}
int position = 0;
while (num > 0) {
num >>= 1;
position++;
}
return Optional.of(position - 1); // Subtract 1 to convert to zero-based index
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCount.java | src/main/java/com/thealgorithms/bitmanipulation/NextHigherSameBitCount.java | package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to find the next higher number
* with the same number of set bits as the given number.
*
* @author Hardvan
*/
public final class NextHigherSameBitCount {
private NextHigherSameBitCount() {
}
/**
* Finds the next higher integer with the same number of set bits.
* Steps:
* 1. Find {@code c}, the rightmost set bit of {@code n}.
* 2. Find {@code r}, the rightmost set bit of {@code n + c}.
* 3. Swap the bits of {@code r} and {@code n} to the right of {@code c}.
* 4. Shift the bits of {@code r} and {@code n} to the right of {@code c} to the rightmost.
* 5. Combine the results of steps 3 and 4.
*
* @param n the input number
* @return the next higher integer with the same set bit count
*/
public static int nextHigherSameBitCount(int n) {
int c = n & -n;
int r = n + c;
return (((r ^ n) >> 2) / c) | r;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/ParityCheck.java | src/main/java/com/thealgorithms/bitmanipulation/ParityCheck.java | package com.thealgorithms.bitmanipulation;
/**
* The ParityCheck class provides a method to check the parity of a given number.
* <p>
* Parity is a mathematical term that describes the property of an integer's binary representation.
* The parity of a binary number is the number of 1s in its binary representation.
* If the number of 1s is even, the parity is even; otherwise, it is odd.
* <p>
* For example, the binary representation of 5 is 101, which has two 1s, so the parity of 5 is even.
* The binary representation of 6 is 110, which has two 1s, so the parity of 6 is even.
* The binary representation of 7 is 111, which has three 1s, so the parity of 7 is odd.
*
* @author Hardvan
*/
public final class ParityCheck {
private ParityCheck() {
}
/**
* This method checks the parity of the given number.
*
* @param n the number to check the parity of
* @return true if the number has even parity, false otherwise
*/
public static boolean checkParity(int n) {
int count = 0;
while (n > 0) {
count += n & 1;
n >>= 1;
}
return count % 2 == 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java | src/main/java/com/thealgorithms/bitmanipulation/FirstDifferentBit.java | package com.thealgorithms.bitmanipulation;
/**
* 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)
* The first differing bit is at index 1 (0-based)
* So, the output will be 1
*
* @author Hardvan
*/
public final class FirstDifferentBit {
private FirstDifferentBit() {
}
/**
* Identifies the index of the first differing bit between two integers.
* Steps:
* 1. XOR the two integers to get the differing bits
* 2. Find the index of the first set bit in XOR result
*
* @param x the first integer
* @param y the second integer
* @return the index of the first differing bit (0-based)
*/
public static int firstDifferentBit(int x, int y) {
int diff = x ^ y;
return Integer.numberOfTrailingZeros(diff);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java | src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class for bit manipulation operations.
* This class provides methods to work with bitwise operations.
* 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)
*/
public final class IndexOfRightMostSetBit {
private IndexOfRightMostSetBit() {
}
/**
* Finds the index of the rightmost set bit in the given integer.
* The index is zero-based, meaning the rightmost bit has an index of 0.
*
* @param n the integer to check for the rightmost set bit
* @return the index of the rightmost set bit; -1 if there are no set bits
* (i.e., the input integer is 0)
*/
public static int indexOfRightMostSetBit(int n) {
if (n == 0) {
return -1; // No set bits
}
// Handle negative numbers by finding the two's complement
if (n < 0) {
n = -n;
n = n & (~n + 1); // Isolate the rightmost set bit
}
int index = 0;
while ((n & 1) == 0) {
n = n >> 1;
index++;
}
return index;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java | src/main/java/com/thealgorithms/bitmanipulation/NumberAppearingOddTimes.java | package com.thealgorithms.bitmanipulation;
/**
* 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)
*/
public final class NumberAppearingOddTimes {
private NumberAppearingOddTimes() {
}
/**
* Finds the element in the array that appears an odd number of times.
*
* @param arr the input array containing integers, where all elements
* except one appear an even number of times.
* @return the integer that appears an odd number of times.
*/
public static int findOddOccurrence(int[] arr) {
int result = 0;
for (int num : arr) {
result ^= num;
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BitRotate.java | src/main/java/com/thealgorithms/bitmanipulation/BitRotate.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class for performing circular bit rotations on 32-bit integers.
* Bit rotation is a circular shift operation where bits shifted out on one end
* are reinserted on the opposite end.
*
* <p>This class provides methods for both left and right circular rotations,
* supporting only 32-bit integer operations with proper shift normalization
* and error handling.</p>
*
* @see <a href="https://en.wikipedia.org/wiki/Bit_rotation">Bit Rotation</a>
*/
public final class BitRotate {
/**
* Private constructor to prevent instantiation.
* This is a utility class with only static methods.
*/
private BitRotate() {
throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
/**
* Performs a circular left rotation (left shift) on a 32-bit integer.
* Bits shifted out from the left side are inserted on the right side.
*
* @param value the 32-bit integer value to rotate
* @param shift the number of positions to rotate left (must be non-negative)
* @return the result of left rotating the value by the specified shift amount
* @throws IllegalArgumentException if shift is negative
*
* @example
* // Binary: 10000000 00000000 00000000 00000001
* rotateLeft(0x80000001, 1)
* // Returns: 3 (binary: 00000000 00000000 00000000 00000011)
*/
public static int rotateLeft(int value, int shift) {
if (shift < 0) {
throw new IllegalArgumentException("Shift amount cannot be negative: " + shift);
}
// Normalize shift to the range [0, 31] using modulo 32
shift = shift % 32;
if (shift == 0) {
return value;
}
// Left rotation: (value << shift) | (value >>> (32 - shift))
return (value << shift) | (value >>> (32 - shift));
}
/**
* Performs a circular right rotation (right shift) on a 32-bit integer.
* Bits shifted out from the right side are inserted on the left side.
*
* @param value the 32-bit integer value to rotate
* @param shift the number of positions to rotate right (must be non-negative)
* @return the result of right rotating the value by the specified shift amount
* @throws IllegalArgumentException if shift is negative
*
* @example
* // Binary: 00000000 00000000 00000000 00000011
* rotateRight(3, 1)
* // Returns: -2147483647 (binary: 10000000 00000000 00000000 00000001)
*/
public static int rotateRight(int value, int shift) {
if (shift < 0) {
throw new IllegalArgumentException("Shift amount cannot be negative: " + shift);
}
// Normalize shift to the range [0, 31] using modulo 32
shift = shift % 32;
if (shift == 0) {
return value;
}
// Right rotation: (value >>> shift) | (value << (32 - shift))
return (value >>> shift) | (value << (32 - shift));
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BitwiseGCD.java | src/main/java/com/thealgorithms/bitmanipulation/BitwiseGCD.java | package com.thealgorithms.bitmanipulation;
import java.math.BigInteger;
/**
* Bitwise GCD implementation with full-range support utilities.
*
* <p>This class provides a fast binary (Stein's) GCD implementation for {@code long}
* inputs and a BigInteger-backed API for full 2's-complement range support (including
* {@code Long.MIN_VALUE}). The {@code long} implementation is efficient and avoids
* division/modulo operations. For edge-cases that overflow signed-64-bit ranges
* (e.g., gcd(Long.MIN_VALUE, 0) = 2^63), use the BigInteger API {@code gcdBig}.
*
* <p>Behaviour:
* <ul>
* <li>{@code gcd(long,long)} : returns non-negative {@code long} gcd for inputs whose
* absolute values fit in signed {@code long} (i.e., not causing an unsigned 2^63 result).
* If the true gcd does not fit in a signed {@code long} (for example gcd(Long.MIN_VALUE,0) = 2^63)
* this method will delegate to BigInteger and throw {@link ArithmeticException} if the
* BigInteger result does not fit into a signed {@code long}.</li>
* <li>{@code gcdBig(BigInteger, BigInteger)} : returns the exact gcd as a {@link BigInteger}
* and works for the full signed-64-bit range and beyond.</li>
* </ul>
*/
public final class BitwiseGCD {
private BitwiseGCD() {
}
/**
* Computes GCD of two long values using Stein's algorithm (binary GCD).
* <p>Handles negative inputs. If either input is {@code Long.MIN_VALUE} the
* method delegates to the BigInteger implementation and will throw {@link ArithmeticException}
* if the result cannot be represented as a signed {@code long}.
*
* @param a first value (may be negative)
* @param b second value (may be negative)
* @return non-negative gcd as a {@code long}
* @throws ArithmeticException when the exact gcd does not fit into a signed {@code long}
*/
public static long gcd(long a, long b) {
// Trivial cases
if (a == 0L) {
return absOrThrowIfOverflow(b);
}
if (b == 0L) {
return absOrThrowIfOverflow(a);
}
// If either is Long.MIN_VALUE, absolute value doesn't fit into signed long.
if (a == Long.MIN_VALUE || b == Long.MIN_VALUE) {
// Delegate to BigInteger and try to return a long if it fits
BigInteger g = gcdBig(BigInteger.valueOf(a), BigInteger.valueOf(b));
return g.longValueExact();
}
// Work with non-negative long values now (safe because we excluded Long.MIN_VALUE)
a = (a < 0) ? -a : a;
b = (b < 0) ? -b : b;
// Count common factors of 2
int commonTwos = Long.numberOfTrailingZeros(a | b);
// Remove all factors of 2 from a
a >>= Long.numberOfTrailingZeros(a);
while (b != 0L) {
// Remove all factors of 2 from b
b >>= Long.numberOfTrailingZeros(b);
// Now both a and b are odd. Ensure a <= b
if (a > b) {
long tmp = a;
a = b;
b = tmp;
}
// b >= a; subtract a from b (result is even)
b = b - a;
}
// Restore common powers of two
return a << commonTwos;
}
/**
* Helper to return absolute value of x unless x == Long.MIN_VALUE, in which
* case we delegate to BigInteger and throw to indicate overflow.
*/
private static long absOrThrowIfOverflow(long x) {
if (x == Long.MIN_VALUE) {
// |Long.MIN_VALUE| = 2^63 which does not fit into signed long
throw new ArithmeticException("Absolute value of Long.MIN_VALUE does not fit into signed long. Use gcdBig() for full-range support.");
}
return (x < 0) ? -x : x;
}
/**
* Computes GCD for an array of {@code long} values. Returns 0 for empty/null arrays.
* If any intermediate gcd cannot be represented in signed long (rare), an ArithmeticException
* will be thrown.
*/
public static long gcd(long... values) {
if (values == null || values.length == 0) {
return 0L;
}
long result = values[0];
for (int i = 1; i < values.length; i++) {
result = gcd(result, values[i]);
if (result == 1L) {
return 1L; // early exit
}
}
return result;
}
/**
* BigInteger-backed gcd that works for the full integer range (and beyond).
* This is the recommended method when inputs may be Long.MIN_VALUE or when you
* need an exact result even if it is greater than Long.MAX_VALUE.
* @param a first value (may be negative)
* @param b second value (may be negative)
* @return non-negative gcd as a {@link BigInteger}
*/
public static BigInteger gcdBig(BigInteger a, BigInteger b) {
if (a == null || b == null) {
throw new NullPointerException("Arguments must not be null");
}
return a.abs().gcd(b.abs());
}
/**
* Convenience overload that accepts signed-64 inputs and returns BigInteger gcd.
*/
public static BigInteger gcdBig(long a, long b) {
return gcdBig(BigInteger.valueOf(a), BigInteger.valueOf(b));
}
/**
* int overload for convenience.
*/
public static int gcd(int a, int b) {
return (int) gcd((long) a, (long) b);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java | src/main/java/com/thealgorithms/bitmanipulation/BcdConversion.java | package com.thealgorithms.bitmanipulation;
/**
* 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
* <a href="https://en.wikipedia.org/wiki/Binary-coded_decimal">Binary-Coded Decimal</a> Wikipedia page.
*
* <b>Example usage:</b>
* <pre>
* int decimal = BcdConversion.bcdToDecimal(0x1234);
* System.out.println("BCD 0x1234 to decimal: " + decimal); // Output: 1234
*
* int bcd = BcdConversion.decimalToBcd(1234);
* System.out.println("Decimal 1234 to BCD: " + Integer.toHexString(bcd)); // Output: 0x1234
* </pre>
*/
public final class BcdConversion {
private BcdConversion() {
}
/**
* Converts a BCD (Binary-Coded Decimal) number to a decimal number.
* <p>Steps:
* <p>1. Validate the BCD number to ensure all digits are between 0 and 9.
* <p>2. Extract the last 4 bits (one BCD digit) from the BCD number.
* <p>3. Multiply the extracted digit by the corresponding power of 10 and add it to the decimal number.
* <p>4. Shift the BCD number right by 4 bits to process the next BCD digit.
* <p>5. Repeat steps 1-4 until the BCD number is zero.
*
* @param bcd The BCD number.
* @return The corresponding decimal number.
* @throws IllegalArgumentException if the BCD number contains invalid digits.
*/
public static int bcdToDecimal(int bcd) {
int decimal = 0;
int multiplier = 1;
// Validate BCD digits
while (bcd > 0) {
int digit = bcd & 0xF;
if (digit > 9) {
throw new IllegalArgumentException("Invalid BCD digit: " + digit);
}
decimal += digit * multiplier;
multiplier *= 10;
bcd >>= 4;
}
return decimal;
}
/**
* Converts a decimal number to BCD (Binary-Coded Decimal).
* <p>Steps:
* <p>1. Check if the decimal number is within the valid range for BCD (0 to 9999).
* <p>2. Extract the last decimal digit from the decimal number.
* <p>3. Shift the digit to the correct BCD position and add it to the BCD number.
* <p>4. Remove the last decimal digit from the decimal number.
* <p>5. Repeat steps 2-4 until the decimal number is zero.
*
* @param decimal The decimal number.
* @return The corresponding BCD number.
* @throws IllegalArgumentException if the decimal number is greater than 9999.
*/
public static int decimalToBcd(int decimal) {
if (decimal < 0 || decimal > 9999) {
throw new IllegalArgumentException("Value out of bounds for BCD representation: " + decimal);
}
int bcd = 0;
int shift = 0;
while (decimal > 0) {
int digit = decimal % 10;
bcd |= (digit << (shift * 4));
decimal /= 10;
shift++;
}
return bcd;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java | src/main/java/com/thealgorithms/bitmanipulation/SwapAdjacentBits.java | package com.thealgorithms.bitmanipulation;
/**
* 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.
* 2. Mask odd-positioned bits: Using `0x55555555` (binary: `010101...`),
* which selects bits in odd positions.
* 3. Shift bits:
* - 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)
*/
public final class SwapAdjacentBits {
private SwapAdjacentBits() {
}
/**
* Swaps every pair of adjacent bits of a given integer.
* Steps:
* 1. Mask the even-positioned bits.
* 2. Mask the odd-positioned bits.
* 3. Shift the even bits to the right and the odd bits to the left.
* 4. Combine the shifted bits.
*
* @param num the integer whose bits are to be swapped
* @return the integer after swapping every pair of adjacent bits
*/
public static int swapAdjacentBits(int num) {
// mask the even bits (0xAAAAAAAA => 10101010...)
int evenBits = num & 0xAAAAAAAA;
// mask the odd bits (0x55555555 => 01010101...)
int oddBits = num & 0x55555555;
// right shift even bits and left shift odd bits
evenBits >>= 1;
oddBits <<= 1;
// combine shifted bits
return evenBits | oddBits;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java | src/main/java/com/thealgorithms/bitmanipulation/OnesComplement.java | package com.thealgorithms.bitmanipulation;
/**
* @author - https://github.com/Monk-AbhinayVerma
* @Wikipedia - https://en.wikipedia.org/wiki/Ones%27_complement
* The class OnesComplement computes the complement of binary number
* and returns
* the complemented binary string.
* @return the complimented binary string
*/
public final class OnesComplement {
private OnesComplement() {
}
/**
* Returns the 1's complement of a binary string.
*
* @param binary A string representing a binary number (e.g., "1010").
* @return A string representing the 1's complement.
* @throws IllegalArgumentException if the input is null or contains characters other than '0' or '1'.
*/
public static String onesComplement(String binary) {
if (binary == null || binary.isEmpty()) {
throw new IllegalArgumentException("Input must be a non-empty binary string.");
}
StringBuilder complement = new StringBuilder(binary.length());
for (char bit : binary.toCharArray()) {
switch (bit) {
case '0' -> complement.append('1');
case '1' -> complement.append('0');
default -> throw new IllegalArgumentException("Input must contain only '0' and '1'. Found: " + bit);
}
}
return complement.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java | src/main/java/com/thealgorithms/bitmanipulation/ReverseBits.java | package com.thealgorithms.bitmanipulation;
/**
* 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.
*
* @author Bama Charan Chhandogi
*/
public final class ReverseBits {
private ReverseBits() {
}
/**
* Reverses the bits of a 32-bit integer.
*
* @param n the integer whose bits are to be reversed
* @return the integer obtained by reversing the bits of the input
*/
public static int reverseBits(int n) {
int result = 0;
int bitCount = 32;
for (int i = 0; i < bitCount; i++) {
result <<= 1; // Left shift the result to make space for the next bit
result |= (n & 1); // OR operation to set the least significant bit of result with the current bit of n
n >>= 1; // Right shift n to move on to the next bit
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/SingleElement.java | src/main/java/com/thealgorithms/bitmanipulation/SingleElement.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class to find the single non-duplicate element from an array
* where all other elements appear twice.
* <p>
* The algorithm runs in O(n) time complexity and O(1) space complexity
* using bitwise XOR.
* </p>
*
* @author <a href="http://github.com/tuhinm2002">Tuhin M</a>
*/
public final class SingleElement {
/**
* Private constructor to prevent instantiation of this utility class.
* Throws an UnsupportedOperationException if attempted.
*/
private SingleElement() {
throw new UnsupportedOperationException("Utility Class");
}
/**
* Finds the single non-duplicate element in an array where every other
* element appears exactly twice. Uses bitwise XOR to achieve O(n) time
* complexity and O(1) space complexity.
*
* @param arr the input array containing integers where every element
* except one appears exactly twice
* @return the single non-duplicate element
*/
public static int findSingleElement(int[] arr) {
int ele = 0;
for (int i = 0; i < arr.length; i++) {
ele ^= arr[i];
}
return ele;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java | src/main/java/com/thealgorithms/bitmanipulation/GenerateSubsets.java | package com.thealgorithms.bitmanipulation;
import java.util.ArrayList;
import java.util.List;
/**
* This class provides a method to generate all subsets (power set)
* of a given set using bit manipulation.
*
* @author Hardvan
*/
public final class GenerateSubsets {
private GenerateSubsets() {
}
/**
* Generates all subsets of a given set using bit manipulation.
* Steps:
* 1. Iterate over all numbers from 0 to 2^n - 1.
* 2. For each number, iterate over all bits from 0 to n - 1.
* 3. If the i-th bit of the number is set, add the i-th element of the set to the current subset.
* 4. Add the current subset to the list of subsets.
* 5. Return the list of subsets.
*
* @param set the input set of integers
* @return a list of all subsets represented as lists of integers
*/
public static List<List<Integer>> generateSubsets(int[] set) {
int n = set.length;
List<List<Integer>> subsets = new ArrayList<>();
for (int mask = 0; mask < (1 << n); mask++) {
List<Integer> subset = new ArrayList<>();
for (int i = 0; i < n; i++) {
if ((mask & (1 << i)) != 0) {
subset.add(set[i]);
}
}
subsets.add(subset);
}
return subsets;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java | src/main/java/com/thealgorithms/bitmanipulation/NumbersDifferentSigns.java | package com.thealgorithms.bitmanipulation;
/**
* 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.
*
* @author Bama Charan Chhandogi
*/
public final class NumbersDifferentSigns {
private NumbersDifferentSigns() {
}
/**
* Determines if two integers have different signs using bitwise XOR.
*
* @param num1 the first integer
* @param num2 the second integer
* @return true if the two numbers have different signs, false otherwise
*/
public static boolean differentSigns(int num1, int num2) {
return (num1 ^ num2) < 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java | src/main/java/com/thealgorithms/bitmanipulation/HigherLowerPowerOfTwo.java | package com.thealgorithms.bitmanipulation;
/**
* HigherLowerPowerOfTwo class has two methods to find the next higher and lower power of two.
* <p>
* nextHigherPowerOfTwo method finds the next higher power of two.
* nextLowerPowerOfTwo method finds the next lower power of two.
* Both methods take an integer as input and return the next higher or lower power of two.
* If the input is less than 1, the next higher power of two is 1.
* If the input is less than or equal to 1, the next lower power of two is 0.
* nextHigherPowerOfTwo method uses bitwise operations to find the next higher power of two.
* nextLowerPowerOfTwo method uses Integer.highestOneBit method to find the next lower power of two.
* The time complexity of both methods is O(1).
* The space complexity of both methods is O(1).
* </p>
*
* @author Hardvan
*/
public final class HigherLowerPowerOfTwo {
private HigherLowerPowerOfTwo() {
}
/**
* Finds the next higher power of two.
*
* @param x The given number.
* @return The next higher power of two.
*/
public static int nextHigherPowerOfTwo(int x) {
if (x < 1) {
return 1;
}
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
}
/**
* Finds the next lower power of two.
*
* @param x The given number.
* @return The next lower power of two.
*/
public static int nextLowerPowerOfTwo(int x) {
if (x < 1) {
return 0;
}
return Integer.highestOneBit(x);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java | src/main/java/com/thealgorithms/bitmanipulation/LowestSetBit.java | package com.thealgorithms.bitmanipulation;
/**
* Lowest Set Bit
* @author Prayas Kumar (https://github.com/prayas7102)
*/
public final class LowestSetBit {
// Private constructor to hide the default public one
private LowestSetBit() {
}
/**
* Isolates the lowest set bit of the given number. For example, if n = 18
* (binary: 10010), the result will be 2 (binary: 00010).
*
* @param n the number whose lowest set bit will be isolated
* @return the isolated lowest set bit of n
*/
public static int isolateLowestSetBit(int n) {
// Isolate the lowest set bit using n & -n
return n & -n;
}
/**
* Clears the lowest set bit of the given number.
* For example, if n = 18 (binary: 10010), the result will be 16 (binary: 10000).
*
* @param n the number whose lowest set bit will be cleared
* @return the number after clearing its lowest set bit
*/
public static int clearLowestSetBit(int n) {
// Clear the lowest set bit using n & (n - 1)
return n & (n - 1);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java | src/main/java/com/thealgorithms/bitmanipulation/NonRepeatingNumberFinder.java | package com.thealgorithms.bitmanipulation;
/**
* 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)
*/
public final class NonRepeatingNumberFinder {
private NonRepeatingNumberFinder() {
}
/**
* Finds the non-repeating number in the given array.
*
* @param arr an array of integers where every number except one appears twice
* @return the integer that appears only once in the array or 0 if the array is empty
*/
public static int findNonRepeatingNumber(int[] arr) {
int result = 0;
for (int num : arr) {
result ^= num;
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java | src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java | package com.thealgorithms.bitmanipulation;
/**
* Gray code is a binary numeral system where two successive values differ in only one bit.
* This is a simple conversion between binary and Gray code.
* Example:
* 7 -> 0111 -> 0100 -> 4
* 4 -> 0100 -> 0111 -> 7
* 0 -> 0000 -> 0000 -> 0
* 1 -> 0001 -> 0000 -> 0
* 2 -> 0010 -> 0011 -> 3
* 3 -> 0011 -> 0010 -> 2
*
* @author Hardvan
*/
public final class GrayCodeConversion {
private GrayCodeConversion() {
}
/**
* Converts a binary number to Gray code.
*
* @param num The binary number.
* @return The corresponding Gray code.
*/
public static int binaryToGray(int num) {
return num ^ (num >> 1);
}
/**
* Converts a Gray code number back to binary.
*
* @param gray The Gray code number.
* @return The corresponding binary number.
*/
public static int grayToBinary(int gray) {
int binary = gray;
while (gray > 0) {
gray >>= 1;
binary ^= gray;
}
return binary;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java | src/main/java/com/thealgorithms/bitmanipulation/IsPowerTwo.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class for checking if a number is a power of two.
* 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)
*/
public final class IsPowerTwo {
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
* (n & (n - 1)) will be zero.
*
* @param number the integer to check
* @return true if the number is a power of two, false otherwise
*/
public static boolean isPowerTwo(int number) {
if (number <= 0) {
return false;
}
int ans = number & (number - 1);
return ans == 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java | src/main/java/com/thealgorithms/bitmanipulation/CountSetBits.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class to count total set bits from 1 to N
* A set bit is a bit in binary representation that is 1
*
* @author navadeep
*/
public final class CountSetBits {
private CountSetBits() {
// Utility class, prevent instantiation
}
/**
* Counts total number of set bits in all numbers from 1 to n
* Time Complexity: O(log n)
*
* @param n the upper limit (inclusive)
* @return total count of set bits from 1 to n
* @throws IllegalArgumentException if n is negative
*/
public static int countSetBits(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input must be non-negative");
}
if (n == 0) {
return 0;
}
// Find the largest power of 2 <= n
int x = largestPowerOf2InNumber(n);
// Total bits at position x: x * 2^(x-1)
int bitsAtPositionX = x * (1 << (x - 1));
// Remaining numbers after 2^x
int remainingNumbers = n - (1 << x) + 1;
// Recursively count for the rest
int rest = countSetBits(n - (1 << x));
return bitsAtPositionX + remainingNumbers + rest;
}
/**
* Finds the position of the most significant bit in n
*
* @param n the number
* @return position of MSB (0-indexed from right)
*/
private static int largestPowerOf2InNumber(int n) {
int position = 0;
while ((1 << position) <= n) {
position++;
}
return position - 1;
}
/**
* Alternative naive approach - counts set bits by iterating through all numbers
* Time Complexity: O(n log n)
*
* @param n the upper limit (inclusive)
* @return total count of set bits from 1 to n
*/
public static int countSetBitsNaive(int n) {
if (n < 0) {
throw new IllegalArgumentException("Input must be non-negative");
}
int count = 0;
for (int i = 1; i <= n; i++) {
count += Integer.bitCount(i);
}
return count;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwo.java | src/main/java/com/thealgorithms/bitmanipulation/ModuloPowerOfTwo.java | package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to compute the remainder
* of a number when divided by a power of two (2^n)
* without using division or modulo operations.
*
* @author Hardvan
*/
public final class ModuloPowerOfTwo {
private ModuloPowerOfTwo() {
}
/**
* Computes the remainder of a given integer when divided by 2^n.
*
* @param x the input number
* @param n the exponent (power of two)
* @return the remainder of x divided by 2^n
*/
public static int moduloPowerOfTwo(int x, int n) {
if (n <= 0) {
throw new IllegalArgumentException("The exponent must be positive");
}
return x & ((1 << n) - 1);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/IsEven.java | src/main/java/com/thealgorithms/bitmanipulation/IsEven.java | package com.thealgorithms.bitmanipulation;
/**
* Checks whether a number is even
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public final class IsEven {
private IsEven() {
}
public static boolean isEven(int number) {
return (number & 1) == 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java | src/main/java/com/thealgorithms/bitmanipulation/CountBitsFlip.java | package com.thealgorithms.bitmanipulation;
/**
* 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)
*
*@author [Yash Rajput](https://github.com/the-yash-rajput)
*/
public final class CountBitsFlip {
private CountBitsFlip() {
throw new AssertionError("No instances.");
}
/**
* 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
* 3. Use Brian Kernighan's algorithm: n & (n-1) removes rightmost set bit
*
* @param a the source number
* @param b the target number
* @return the number of bits to flip to convert A to B
*/
public static long countBitsFlip(long a, long b) {
int count = 0;
// XOR gives us positions where bits differ
long xorResult = a ^ b;
// Count set bits using Brian Kernighan's algorithm
while (xorResult != 0) {
xorResult = xorResult & (xorResult - 1); // Remove rightmost set bit
count++;
}
return count;
}
/**
* Alternative implementation using Long.bitCount().
*
* @param a the source number
* @param b the target number
* @return the number of bits to flip to convert a to b
*/
public static long countBitsFlipAlternative(long a, long b) {
return Long.bitCount(a ^ b);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/CountLeadingZeros.java | src/main/java/com/thealgorithms/bitmanipulation/CountLeadingZeros.java | package com.thealgorithms.bitmanipulation;
/**
* CountLeadingZeros class contains a method to count the number of leading zeros in the binary representation of a number.
* The number of leading zeros is the number of zeros before the leftmost 1 bit.
* For example, the number 5 has 29 leading zeros in its 32-bit binary representation.
* The number 0 has 32 leading zeros.
* The number 1 has 31 leading zeros.
* The number -1 has no leading zeros.
*
* @author Hardvan
*/
public final class CountLeadingZeros {
private CountLeadingZeros() {
}
/**
* Counts the number of leading zeros in the binary representation of a number.
* Method: Keep shifting the mask to the right until the leftmost bit is 1.
* The number of shifts is the number of leading zeros.
*
* @param num The input number.
* @return The number of leading zeros.
*/
public static int countLeadingZeros(int num) {
if (num == 0) {
return 32;
}
int count = 0;
int mask = 1 << 31;
while ((mask & num) == 0) {
count++;
mask >>>= 1;
}
return count;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java | src/main/java/com/thealgorithms/bitmanipulation/TwosComplement.java | package com.thealgorithms.bitmanipulation;
/**
* This class provides a method to compute the Two's Complement of a given binary number.
*
* <p>In two's complement representation, a binary number's negative value is obtained
* by taking the one's complement (inverting all bits) and then adding 1 to the result.
* This method handles both small and large binary strings and ensures the output is
* correct for all binary inputs, including edge cases like all zeroes and all ones.
*
* <p>For more information on Two's Complement:
* @see <a href="https://en.wikipedia.org/wiki/Two%27s_complement">Wikipedia - Two's Complement</a>
*
* <p>Algorithm originally suggested by Jon von Neumann.
*
* @author Abhinay Verma (https://github.com/Monk-AbhinayVerma)
*/
public final class TwosComplement {
private TwosComplement() {
}
/**
* Computes the Two's Complement of the given binary string.
* Steps:
* 1. Compute the One's Complement (invert all bits).
* 2. Add 1 to the One's Complement to get the Two's Complement.
* 3. Iterate from the rightmost bit to the left, adding 1 and carrying over as needed.
* 4. If a carry is still present after the leftmost bit, prepend '1' to handle overflow.
*
* @param binary The binary number as a string (only '0' and '1' characters allowed).
* @return The two's complement of the input binary string as a new binary string.
* @throws IllegalArgumentException If the input contains non-binary characters.
*/
public static String twosComplement(String binary) {
if (!binary.matches("[01]+")) {
throw new IllegalArgumentException("Input must contain only '0' and '1'.");
}
StringBuilder onesComplement = new StringBuilder();
for (char bit : binary.toCharArray()) {
onesComplement.append(bit == '0' ? '1' : '0');
}
StringBuilder twosComplement = new StringBuilder(onesComplement);
boolean carry = true;
for (int i = onesComplement.length() - 1; i >= 0 && carry; i--) {
if (onesComplement.charAt(i) == '1') {
twosComplement.setCharAt(i, '0');
} else {
twosComplement.setCharAt(i, '1');
carry = false;
}
}
if (carry) {
twosComplement.insert(0, '1');
}
return twosComplement.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java | src/main/java/com/thealgorithms/bitmanipulation/SingleBitOperations.java | package com.thealgorithms.bitmanipulation;
/**
* 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)
*/
public final class SingleBitOperations {
private SingleBitOperations() {
}
/**
* Flips (toggles) the bit at the specified position.
*
* @param num the input number
* @param bit the position of the bit to flip (0-indexed)
* @return the new number after flipping the specified bit
*/
public static int flipBit(final int num, final int bit) {
return num ^ (1 << bit);
}
/**
* Sets the bit at the specified position to 1.
*
* @param num the input number
* @param bit the position of the bit to set (0-indexed)
* @return the new number after setting the specified bit to 1
*/
public static int setBit(final int num, final int bit) {
return num | (1 << bit);
}
/**
* Clears the bit at the specified position (sets it to 0).
*
* @param num the input number
* @param bit the position of the bit to clear (0-indexed)
* @return the new number after clearing the specified bit
*/
public static int clearBit(final int num, final int bit) {
return num & ~(1 << bit);
}
/**
* Gets the bit value (0 or 1) at the specified position.
*
* @param num the input number
* @param bit the position of the bit to retrieve (0-indexed)
* @return 1 if the bit is set, 0 otherwise
*/
public static int getBit(final int num, final int bit) {
return (num >> bit) & 1;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java | src/main/java/com/thealgorithms/bitmanipulation/FindNthBit.java | package com.thealgorithms.bitmanipulation;
/**
* A utility class to find the Nth bit of a given number.
*
* <p>This class provides a method to extract the value of the Nth bit (either 0 or 1)
* from the binary representation of a given integer.
*
* <p>Example:
* <pre>{@code
* int result = FindNthBit.findNthBit(5, 2); // returns 0 as the 2nd bit of 5 (binary 101) is 0.
* }</pre>
*
* <p>Author: <a href="https://github.com/Tuhinm2002">Tuhinm2002</a>
*/
public final class FindNthBit {
/**
* Private constructor to prevent instantiation.
*
* <p>This is a utility class, and it should not be instantiated.
* Attempting to instantiate this class will throw an UnsupportedOperationException.
*/
private FindNthBit() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Finds the value of the Nth bit of the given number.
*
* <p>This method uses bitwise operations to extract the Nth bit from the
* binary representation of the given integer.
*
* @param num the integer number whose Nth bit is to be found
* @param n the bit position (1-based) to retrieve
* @return the value of the Nth bit (0 or 1)
* @throws IllegalArgumentException if the bit position is less than 1
*/
public static int findNthBit(int num, int n) {
if (n < 1) {
throw new IllegalArgumentException("Bit position must be greater than or equal to 1.");
}
// Shifting the number to the right by (n - 1) positions and checking the last bit
return (num & (1 << (n - 1))) >> (n - 1);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java | src/main/java/com/thealgorithms/bitmanipulation/BitSwap.java | package com.thealgorithms.bitmanipulation;
/**
* Utility class for performing bit-swapping operations on integers.
* This class cannot be instantiated.
*/
public final class BitSwap {
private BitSwap() {
}
/**
* Swaps two bits at specified positions in an integer.
*
* @param data The input integer whose bits need to be swapped
* @param posA The position of the first bit (0-based, from least significant)
* @param posB The position of the second bit (0-based, from least significant)
* @return The modified value with swapped bits
* @throws IllegalArgumentException if either position is negative or ≥ 32
*/
public static int bitSwap(int data, final int posA, final int posB) {
if (posA < 0 || posA >= Integer.SIZE || posB < 0 || posB >= Integer.SIZE) {
throw new IllegalArgumentException("Bit positions must be between 0 and 31");
}
boolean bitA = ((data >> posA) & 1) != 0;
boolean bitB = ((data >> posB) & 1) != 0;
if (bitA != bitB) {
data ^= (1 << posA) ^ (1 << posB);
}
return data;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java | src/main/java/com/thealgorithms/bitmanipulation/BinaryPalindromeCheck.java | package com.thealgorithms.bitmanipulation;
/**
* This class contains a method to check if the binary representation of a number is a palindrome.
* <p>
* A binary palindrome is a number whose binary representation is the same when read from left to right and right to left.
* For example, the number 9 has a binary representation of 1001, which is a palindrome.
* The number 10 has a binary representation of 1010, which is not a palindrome.
* </p>
*
* @author Hardvan
*/
public final class BinaryPalindromeCheck {
private BinaryPalindromeCheck() {
}
/**
* Checks if the binary representation of a number is a palindrome.
*
* @param x The number to check.
* @return True if the binary representation is a palindrome, otherwise false.
*/
public static boolean isBinaryPalindrome(int x) {
int reversed = reverseBits(x);
return x == reversed;
}
/**
* Helper function to reverse all the bits of an integer.
*
* @param x The number to reverse the bits of.
* @return The number with reversed bits.
*/
private static int reverseBits(int x) {
int result = 0;
while (x > 0) {
result <<= 1;
result |= (x & 1);
x >>= 1;
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java | src/main/java/com/thealgorithms/bitmanipulation/Xs3Conversion.java | package com.thealgorithms.bitmanipulation;
/**
* 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
* <a href="https://en.wikipedia.org/wiki/Excess-3">Excess-3</a> Wikipedia page.
*
* <b>Example usage:</b>
* <pre>
* int binary = Xs3Conversion.xs3ToBinary(0x4567);
* System.out.println("XS-3 0x4567 to binary: " + binary); // Output: 1234
*
* int xs3 = Xs3Conversion.binaryToXs3(1234);
* System.out.println("Binary 1234 to XS-3: " + Integer.toHexString(xs3)); // Output: 0x4567
* </pre>
*/
public final class Xs3Conversion {
private Xs3Conversion() {
}
/**
* Converts an XS-3 (Excess-3) number to binary.
*
* @param xs3 The XS-3 number.
* @return The corresponding binary number.
*/
public static int xs3ToBinary(int xs3) {
int binary = 0;
int multiplier = 1;
while (xs3 > 0) {
int digit = (xs3 & 0xF) - 3; // Extract the last 4 bits (one XS-3 digit) and subtract 3
binary += digit * multiplier;
multiplier *= 10;
xs3 >>= 4; // Shift right by 4 bits to process the next XS-3 digit
}
return binary;
}
/**
* Converts a binary number to XS-3 (Excess-3).
*
* @param binary The binary number.
* @return The corresponding XS-3 number.
*/
public static int binaryToXs3(int binary) {
int xs3 = 0;
int shift = 0;
while (binary > 0) {
int digit = (binary % 10) + 3; // Extract the last decimal digit and add 3
xs3 |= (digit << (shift * 4)); // Shift the digit to the correct XS-3 position
binary /= 10; // Remove the last decimal digit
shift++;
}
return xs3;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/ShannonFano.java | src/main/java/com/thealgorithms/compression/ShannonFano.java | package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* An implementation of the Shannon-Fano algorithm for generating prefix codes.
*
* <p>Shannon-Fano coding is an entropy encoding technique for lossless data
* compression. It assigns variable-length codes to symbols based on their
* frequencies of occurrence. It is a precursor to Huffman coding and works by
* recursively partitioning a sorted list of symbols into two sub-lists with
* nearly equal total frequencies.
*
* <p>The algorithm works as follows:
* <ol>
* <li>Count the frequency of each symbol in the input data.</li>
* <li>Sort the symbols in descending order of their frequencies.</li>
* <li>Recursively divide the list of symbols into two parts with sums of
* frequencies as close as possible to each other.</li>
* <li>Assign a '0' bit to the codes in the first part and a '1' bit to the codes
* in the second part.</li>
* <li>Repeat the process for each part until a part contains only one symbol.</li>
* </ol>
*
* <p>Time Complexity: O(n^2) in this implementation due to the partitioning logic,
* or O(n log n) if a more optimized partitioning strategy is used.
* Sorting takes O(n log n), where n is the number of unique symbols.
*
* <p>References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/Shannonâ€"Fano_coding">Wikipedia: Shannonâ€"Fano coding</a></li>
* </ul>
*/
public final class ShannonFano {
/**
* Private constructor to prevent instantiation of this utility class.
*/
private ShannonFano() {
}
/**
* A private inner class to represent a symbol and its frequency.
* Implements Comparable to allow sorting based on frequency.
*/
private static class Symbol implements Comparable<Symbol> {
final char character;
final int frequency;
String code = "";
Symbol(char character, int frequency) {
this.character = character;
this.frequency = frequency;
}
@Override
public int compareTo(Symbol other) {
return Integer.compare(other.frequency, this.frequency); // Sort descending
}
}
/**
* Generates Shannon-Fano codes for the symbols in a given text.
*
* @param text The input string for which to generate codes. Must not be null.
* @return A map where keys are characters and values are their corresponding Shannon-Fano codes.
*/
public static Map<Character, String> generateCodes(String text) {
if (text == null || text.isEmpty()) {
return Collections.emptyMap();
}
Map<Character, Integer> frequencyMap = new HashMap<>();
for (char c : text.toCharArray()) {
frequencyMap.put(c, frequencyMap.getOrDefault(c, 0) + 1);
}
List<Symbol> symbols = new ArrayList<>();
for (Map.Entry<Character, Integer> entry : frequencyMap.entrySet()) {
symbols.add(new Symbol(entry.getKey(), entry.getValue()));
}
Collections.sort(symbols);
// Special case: only one unique symbol
if (symbols.size() == 1) {
symbols.getFirst().code = "0";
} else {
buildCodeTree(symbols, 0, symbols.size() - 1, "");
}
return symbols.stream().collect(Collectors.toMap(s -> s.character, s -> s.code));
}
/**
* Recursively builds the Shannon-Fano code tree by partitioning the list of symbols.
* Uses index-based approach to avoid sublist creation issues.
*
* @param symbols The sorted list of symbols to be processed.
* @param start The start index of the current partition.
* @param end The end index of the current partition (inclusive).
* @param prefix The current prefix code being built for the symbols in this partition.
*/
private static void buildCodeTree(List<Symbol> symbols, int start, int end, String prefix) {
// The initial check in generateCodes ensures start <= end is always true here.
// The base case is when a partition has only one symbol.
if (start == end) {
symbols.get(start).code = prefix;
return;
}
// Find the optimal split point
int splitIndex = findSplitIndex(symbols, start, end);
// Recursively process left and right partitions with updated prefixes
buildCodeTree(symbols, start, splitIndex, prefix + "0");
buildCodeTree(symbols, splitIndex + 1, end, prefix + "1");
}
/**
* Finds the index that splits the range into two parts with the most balanced frequency sums.
* This method tries every possible split point and returns the index that minimizes the
* absolute difference between the two partition sums.
*
* @param symbols The sorted list of symbols.
* @param start The start index of the range.
* @param end The end index of the range (inclusive).
* @return The index of the last element in the first partition.
*/
private static int findSplitIndex(List<Symbol> symbols, int start, int end) {
// Calculate total frequency for the entire range
long totalFrequency = 0;
for (int i = start; i <= end; i++) {
totalFrequency += symbols.get(i).frequency;
}
long leftSum = 0;
long minDifference = Long.MAX_VALUE;
int splitIndex = start;
// Try every possible split point and find the one with minimum difference
for (int i = start; i < end; i++) {
leftSum += symbols.get(i).frequency;
long rightSum = totalFrequency - leftSum;
long difference = Math.abs(leftSum - rightSum);
if (difference < minDifference) {
minDifference = difference;
splitIndex = i;
}
}
return splitIndex;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/LZ78.java | src/main/java/com/thealgorithms/compression/LZ78.java | package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An implementation of the Lempel-Ziv 78 (LZ78) compression algorithm.
* <p>
* LZ78 is a dictionary-based lossless data compression algorithm. It processes
* input data sequentially, building a dictionary of phrases encountered so far.
* It outputs pairs (dictionary_index, next_character), representing
* the longest match found in the dictionary plus the character that follows it.
* </p>
* <p>
* This implementation builds the dictionary dynamically during compression.
* The dictionary index 0 represents the empty string (no prefix).
* </p>
* <p>
* Time Complexity: O(n) on average for compression and decompression, assuming
* efficient dictionary lookups (using a HashMap), where n is the
* length of the input string.
* </p>
* <p>
* References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ78">Wikipedia: LZ78</a></li>
* </ul>
* </p>
*/
public final class LZ78 {
/**
* Special character used to mark end of stream when needed.
*/
private static final char END_OF_STREAM = '\u0000';
/**
* Private constructor to prevent instantiation of this utility class.
*/
private LZ78() {
}
/**
* Represents a token in the LZ78 compressed output.
* Stores the index of the matching prefix in the dictionary and the next character.
* Index 0 represents the empty string (no prefix).
*/
public record Token(int index, char nextChar) {
}
/**
* A node in the dictionary trie structure.
* Each node represents a phrase and can have child nodes for extended phrases.
*/
private static final class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
int index = -1; // -1 means not assigned yet
}
/**
* Compresses the input text using the LZ78 algorithm.
*
* @param text The input string to compress. Must not be null.
* @return A list of {@link Token} objects representing the compressed data.
*/
public static List<Token> compress(String text) {
if (text == null || text.isEmpty()) {
return new ArrayList<>();
}
List<Token> compressedOutput = new ArrayList<>();
TrieNode root = new TrieNode();
int nextDictionaryIndex = 1;
TrieNode currentNode = root;
int lastMatchedIndex = 0;
for (int i = 0; i < text.length(); i++) {
char currentChar = text.charAt(i);
if (currentNode.children.containsKey(currentChar)) {
currentNode = currentNode.children.get(currentChar);
lastMatchedIndex = currentNode.index;
} else {
// Output: (index of longest matching prefix, current character)
compressedOutput.add(new Token(lastMatchedIndex, currentChar));
TrieNode newNode = new TrieNode();
newNode.index = nextDictionaryIndex++;
currentNode.children.put(currentChar, newNode);
currentNode = root;
lastMatchedIndex = 0;
}
}
// Handle remaining phrase at end of input
if (currentNode != root) {
compressedOutput.add(new Token(lastMatchedIndex, END_OF_STREAM));
}
return compressedOutput;
}
/**
* Decompresses a list of LZ78 tokens back into the original string.
*
* @param compressedData The list of {@link Token} objects. Must not be null.
* @return The original, uncompressed string.
*/
public static String decompress(List<Token> compressedData) {
if (compressedData == null || compressedData.isEmpty()) {
return "";
}
StringBuilder decompressedText = new StringBuilder();
Map<Integer, String> dictionary = new HashMap<>();
int nextDictionaryIndex = 1;
for (Token token : compressedData) {
String prefix = (token.index == 0) ? "" : dictionary.get(token.index);
if (token.nextChar == END_OF_STREAM) {
decompressedText.append(prefix);
} else {
String currentPhrase = prefix + token.nextChar;
decompressedText.append(currentPhrase);
dictionary.put(nextDictionaryIndex++, currentPhrase);
}
}
return decompressedText.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/ArithmeticCoding.java | src/main/java/com/thealgorithms/compression/ArithmeticCoding.java | package com.thealgorithms.compression;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An implementation of the Arithmetic Coding algorithm.
*
* <p>
* Arithmetic coding is a form of entropy encoding used in lossless data
* compression. It encodes an entire message into a single number, a fraction n
* where (0.0 <= n < 1.0). Unlike Huffman coding, which assigns a specific
* bit sequence to each symbol, arithmetic coding represents the message as a
* sub-interval of the [0, 1) interval.
* </p>
*
* <p>
* This implementation uses BigDecimal for precision to handle the shrinking
* intervals, making it suitable for educational purposes to demonstrate the
* core logic.
* </p>
*
* <p>
* Time Complexity: O(n*m) for compression and decompression where n is the
* length of the input and m is the number of unique symbols, due to the need
* to calculate symbol probabilities.
* </p>
*
* <p>
* References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/Arithmetic_coding">Wikipedia:
* Arithmetic coding</a></li>
* </ul>
* </p>
*/
public final class ArithmeticCoding {
private ArithmeticCoding() {
}
/**
* Compresses a string using the Arithmetic Coding algorithm.
*
* @param uncompressed The string to be compressed.
* @return The compressed representation as a BigDecimal number.
* @throws IllegalArgumentException if the input string is null or empty.
*/
public static BigDecimal compress(String uncompressed) {
if (uncompressed == null || uncompressed.isEmpty()) {
throw new IllegalArgumentException("Input string cannot be null or empty.");
}
Map<Character, Symbol> probabilityTable = calculateProbabilities(uncompressed);
BigDecimal low = BigDecimal.ZERO;
BigDecimal high = BigDecimal.ONE;
for (char symbol : uncompressed.toCharArray()) {
BigDecimal range = high.subtract(low);
Symbol sym = probabilityTable.get(symbol);
high = low.add(range.multiply(sym.high()));
low = low.add(range.multiply(sym.low()));
}
return low; // Return the lower bound of the final interval
}
/**
* Decompresses a BigDecimal number back into the original string.
*
* @param compressed The compressed BigDecimal number.
* @param length The length of the original uncompressed string.
* @param probabilityTable The probability table used during compression.
* @return The original, uncompressed string.
*/
public static String decompress(BigDecimal compressed, int length, Map<Character, Symbol> probabilityTable) {
StringBuilder decompressed = new StringBuilder();
// Create a sorted list of symbols for deterministic decompression, matching the
// order used in calculateProbabilities
List<Map.Entry<Character, Symbol>> sortedSymbols = new ArrayList<>(probabilityTable.entrySet());
sortedSymbols.sort(Map.Entry.comparingByKey());
BigDecimal low = BigDecimal.ZERO;
BigDecimal high = BigDecimal.ONE;
for (int i = 0; i < length; i++) {
BigDecimal range = high.subtract(low);
// Find which symbol the compressed value falls into
for (Map.Entry<Character, Symbol> entry : sortedSymbols) {
Symbol sym = entry.getValue();
// Calculate the actual range for this symbol in the current interval
BigDecimal symLow = low.add(range.multiply(sym.low()));
BigDecimal symHigh = low.add(range.multiply(sym.high()));
// Check if the compressed value falls within this symbol's range
if (compressed.compareTo(symLow) >= 0 && compressed.compareTo(symHigh) < 0) {
decompressed.append(entry.getKey());
// Update the interval for the next iteration
low = symLow;
high = symHigh;
break;
}
}
}
return decompressed.toString();
}
/**
* Calculates the frequency and probability range for each character in the
* input string in a deterministic order.
*
* @param text The input string.
* @return A map from each character to a Symbol object containing its
* probability range.
*/
public static Map<Character, Symbol> calculateProbabilities(String text) {
Map<Character, Integer> frequencies = new HashMap<>();
for (char c : text.toCharArray()) {
frequencies.put(c, frequencies.getOrDefault(c, 0) + 1);
}
// Sort the characters to ensure a deterministic order for the probability table
List<Character> sortedKeys = new ArrayList<>(frequencies.keySet());
Collections.sort(sortedKeys);
Map<Character, Symbol> probabilityTable = new HashMap<>();
BigDecimal currentLow = BigDecimal.ZERO;
int total = text.length();
for (char symbol : sortedKeys) {
BigDecimal probability = BigDecimal.valueOf(frequencies.get(symbol)).divide(BigDecimal.valueOf(total), MathContext.DECIMAL128);
BigDecimal high = currentLow.add(probability);
probabilityTable.put(symbol, new Symbol(currentLow, high));
currentLow = high;
}
return probabilityTable;
}
/**
* Helper class to store the probability range [low, high) for a symbol.
*/
public record Symbol(BigDecimal low, BigDecimal high) {
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/RunLengthEncoding.java | src/main/java/com/thealgorithms/compression/RunLengthEncoding.java | package com.thealgorithms.compression;
/**
* An implementation of the Run-Length Encoding (RLE) algorithm.
*
* <p>Run-Length Encoding is a simple form of lossless data compression in which
* runs of data (sequences in which the same data value occurs in many
* consecutive data elements) are stored as a single data value and count,
* rather than as the original run.
*
* <p>This implementation provides methods for both compressing and decompressing
* a string. For example:
* <ul>
* <li>Compressing "AAAABBBCCDAA" results in "4A3B2C1D2A".</li>
* <li>Decompressing "4A3B2C1D2A" results in "AAAABBBCCDAA".</li>
* </ul>
*
* <p>Time Complexity: O(n) for both compression and decompression, where n is the
* length of the input string.
*
* <p>References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/Run-length_encoding">Wikipedia: Run-length encoding</a></li>
* </ul>
*/
public final class RunLengthEncoding {
/**
* Private constructor to prevent instantiation of this utility class.
*/
private RunLengthEncoding() {
}
/**
* Compresses a string using the Run-Length Encoding algorithm.
*
* @param text The string to be compressed. Must not be null.
* @return The compressed string. Returns an empty string if the input is empty.
*/
public static String compress(String text) {
if (text == null || text.isEmpty()) {
return "";
}
StringBuilder compressed = new StringBuilder();
int count = 1;
for (int i = 0; i < text.length(); i++) {
// Check if it's the last character or if the next character is different
if (i == text.length() - 1 || text.charAt(i) != text.charAt(i + 1)) {
compressed.append(count);
compressed.append(text.charAt(i));
count = 1; // Reset count for the new character
} else {
count++;
}
}
return compressed.toString();
}
/**
* Decompresses a string that was compressed using the Run-Length Encoding algorithm.
*
* @param compressedText The compressed string. Must not be null.
* @return The original, uncompressed string.
*/
public static String decompress(String compressedText) {
if (compressedText == null || compressedText.isEmpty()) {
return "";
}
StringBuilder decompressed = new StringBuilder();
int count = 0;
for (char ch : compressedText.toCharArray()) {
if (Character.isDigit(ch)) {
// Build the number for runs of 10 or more (e.g., "12A")
count = count * 10 + ch - '0';
} else {
// Append the character 'count' times
decompressed.append(String.valueOf(ch).repeat(Math.max(0, count)));
count = 0; // Reset count for the next sequence
}
}
return decompressed.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/LZ77.java | src/main/java/com/thealgorithms/compression/LZ77.java | package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.List;
/**
* An implementation of the Lempel-Ziv 77 (LZ77) compression algorithm.
* <p>
* LZ77 is a lossless data compression algorithm that works by finding repeated
* occurrences of data in a sliding window. It replaces subsequent occurrences
* with references (offset, length) to the first occurrence within the window.
* </p>
* <p>
* This implementation uses a simple sliding window and lookahead buffer approach.
* Output format is a sequence of tuples (offset, length, next_character).
* </p>
* <p>
* Time Complexity: O(n*W) in this naive implementation, where n is the input length
* and W is the window size, due to the search for the longest match. More advanced
* data structures (like suffix trees) can improve this.
* </p>
* <p>
* References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77">Wikipedia: LZ77</a></li>
* </ul>
* </p>
*/
public final class LZ77 {
private static final int DEFAULT_WINDOW_SIZE = 4096;
private static final int DEFAULT_LOOKAHEAD_BUFFER_SIZE = 16;
private static final char END_OF_STREAM = '\u0000';
private LZ77() {
}
/**
* Represents a token in the LZ77 compressed output.
* Stores the offset back into the window, the length of the match,
* and the next character after the match (or END_OF_STREAM if at end).
*/
public record Token(int offset, int length, char nextChar) {
}
/**
* Compresses the input text using the LZ77 algorithm.
*
* @param text The input string to compress. Must not be null.
* @param windowSize The size of the sliding window (search buffer). Must be positive.
* @param lookaheadBufferSize The size of the lookahead buffer. Must be positive.
* @return A list of {@link Token} objects representing the compressed data.
* @throws IllegalArgumentException if windowSize or lookaheadBufferSize are not positive.
*/
public static List<Token> compress(String text, int windowSize, int lookaheadBufferSize) {
if (text == null) {
return new ArrayList<>();
}
if (windowSize <= 0 || lookaheadBufferSize <= 0) {
throw new IllegalArgumentException("Window size and lookahead buffer size must be positive.");
}
List<Token> compressedOutput = new ArrayList<>();
int currentPosition = 0;
while (currentPosition < text.length()) {
int bestMatchDistance = 0;
int bestMatchLength = 0;
// Define the start of the search window
int searchBufferStart = Math.max(0, currentPosition - windowSize);
// Define the end of the lookahead buffer (don't go past text length)
int lookaheadEnd = Math.min(currentPosition + lookaheadBufferSize, text.length());
// Search for the longest match in the window
for (int i = searchBufferStart; i < currentPosition; i++) {
int currentMatchLength = 0;
// Check how far the match extends into the lookahead buffer
// This allows for overlapping matches (e.g., "aaa" can match with offset 1)
while (currentPosition + currentMatchLength < lookaheadEnd) {
int sourceIndex = i + currentMatchLength;
// Handle overlapping matches (run-length encoding within LZ77)
// When we've matched beyond our starting position, wrap around using modulo
if (sourceIndex >= currentPosition) {
int offset = currentPosition - i;
sourceIndex = i + (currentMatchLength % offset);
}
if (text.charAt(sourceIndex) == text.charAt(currentPosition + currentMatchLength)) {
currentMatchLength++;
} else {
break;
}
}
// If this match is longer than the best found so far
if (currentMatchLength > bestMatchLength) {
bestMatchLength = currentMatchLength;
bestMatchDistance = currentPosition - i; // Calculate offset from current position
}
}
char nextChar;
if (currentPosition + bestMatchLength < text.length()) {
nextChar = text.charAt(currentPosition + bestMatchLength);
} else {
nextChar = END_OF_STREAM;
}
// Add the token to the output
compressedOutput.add(new Token(bestMatchDistance, bestMatchLength, nextChar));
// Move the current position forward
// If we're at the end and had a match, just move by the match length
if (nextChar == END_OF_STREAM) {
currentPosition += bestMatchLength;
} else {
currentPosition += bestMatchLength + 1;
}
}
return compressedOutput;
}
/**
* Compresses the input text using the LZ77 algorithm with default buffer sizes.
*
* @param text The input string to compress. Must not be null.
* @return A list of {@link Token} objects representing the compressed data.
*/
public static List<Token> compress(String text) {
return compress(text, DEFAULT_WINDOW_SIZE, DEFAULT_LOOKAHEAD_BUFFER_SIZE);
}
/**
* Decompresses a list of LZ77 tokens back into the original string.
*
* @param compressedData The list of {@link Token} objects. Must not be null.
* @return The original, uncompressed string.
*/
public static String decompress(List<Token> compressedData) {
if (compressedData == null) {
return "";
}
StringBuilder decompressedText = new StringBuilder();
for (Token token : compressedData) {
// Copy matched characters from the sliding window
if (token.length > 0) {
int startIndex = decompressedText.length() - token.offset;
// Handle overlapping matches (e.g., when length > offset)
for (int i = 0; i < token.length; i++) {
decompressedText.append(decompressedText.charAt(startIndex + i));
}
}
// Append the next character (if not END_OF_STREAM)
if (token.nextChar != END_OF_STREAM) {
decompressedText.append(token.nextChar);
}
}
return decompressedText.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/BurrowsWheelerTransform.java | src/main/java/com/thealgorithms/compression/BurrowsWheelerTransform.java | package com.thealgorithms.compression;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of the Burrows-Wheeler Transform (BWT) and its inverse.
* <p>
* BWT is a reversible data transformation algorithm that rearranges a string into runs of
* similar characters. While not a compression algorithm itself, it significantly improves
* the compressibility of data for subsequent algorithms like Move-to-Front encoding and
* Run-Length Encoding.
* </p>
*
* <p>The transform works by:
* <ol>
* <li>Generating all rotations of the input string</li>
* <li>Sorting these rotations lexicographically</li>
* <li>Taking the last column of the sorted matrix as output</li>
* <li>Recording the index of the original string in the sorted matrix</li>
* </ol>
* </p>
*
* <p><b>Important:</b> The input string should end with a unique end-of-string marker
* (typically '$') that:
* <ul>
* <li>Does not appear anywhere else in the text</li>
* <li>Is lexicographically smaller than all other characters</li>
* <li>Ensures unique rotations and enables correct inverse transformation</li>
* </ul>
* Without this marker, the inverse transform may not correctly reconstruct the original string.
* </p>
*
* <p><b>Time Complexity:</b>
* <ul>
* <li>Forward transform: O(n² log n) where n is the string length</li>
* <li>Inverse transform: O(n) using the LF-mapping technique</li>
* </ul>
* </p>
*
* <p><b>Example:</b></p>
* <pre>
* Input: "banana$"
* Output: BWTResult("annb$aa", 4)
* - "annb$aa" is the transformed string (groups similar characters)
* - 4 is the index of the original string in the sorted rotations
* </pre>
*
* @see <a href="https://en.wikipedia.org/wiki/Burrows%E2%80%93Wheeler_transform">Burrows–Wheeler transform (Wikipedia)</a>
*/
public final class BurrowsWheelerTransform {
private BurrowsWheelerTransform() {
}
/**
* A container for the result of the forward BWT.
* <p>
* Contains the transformed string and the index of the original string
* in the sorted rotations matrix, both of which are required for the
* inverse transformation.
* </p>
*/
public static class BWTResult {
/** The transformed string (last column of the sorted rotation matrix) */
public final String transformed;
/** The index of the original string in the sorted rotations matrix */
public final int originalIndex;
/**
* Constructs a BWTResult with the transformed string and original index.
*
* @param transformed the transformed string (L-column)
* @param originalIndex the index of the original string in sorted rotations
*/
public BWTResult(String transformed, int originalIndex) {
this.transformed = transformed;
this.originalIndex = originalIndex;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
BWTResult bwtResult = (BWTResult) obj;
return originalIndex == bwtResult.originalIndex && transformed.equals(bwtResult.transformed);
}
@Override
public int hashCode() {
return 31 * transformed.hashCode() + originalIndex;
}
@Override
public String toString() {
return "BWTResult[transformed=" + transformed + ", originalIndex=" + originalIndex + "]";
}
}
/**
* Performs the forward Burrows-Wheeler Transform on the input string.
* <p>
* The algorithm generates all cyclic rotations of the input, sorts them
* lexicographically, and returns the last column of this sorted matrix
* along with the position of the original string.
* </p>
*
* <p><b>Note:</b> It is strongly recommended that the input string ends with
* a unique end-of-string marker (e.g., '$') that is lexicographically smaller
* than any other character in the string. This ensures correct inversion.</p>
*
* @param text the input string to transform; must not be {@code null}
* @return a {@link BWTResult} object containing the transformed string (L-column)
* and the index of the original string in the sorted rotations matrix;
* returns {@code BWTResult("", -1)} for empty input
* @throws NullPointerException if {@code text} is {@code null}
*/
public static BWTResult transform(String text) {
if (text == null || text.isEmpty()) {
return new BWTResult("", -1);
}
int n = text.length();
// Generate all rotations of the input string
String[] rotations = new String[n];
for (int i = 0; i < n; i++) {
rotations[i] = text.substring(i) + text.substring(0, i);
}
// Sort rotations lexicographically
Arrays.sort(rotations);
int originalIndex = Arrays.binarySearch(rotations, text);
StringBuilder lastColumn = new StringBuilder(n);
for (int i = 0; i < n; i++) {
lastColumn.append(rotations[i].charAt(n - 1));
}
return new BWTResult(lastColumn.toString(), originalIndex);
}
/**
* Performs the inverse Burrows-Wheeler Transform using the LF-mapping technique.
* <p>
* The LF-mapping (Last-First mapping) is an efficient method to reconstruct
* the original string from the BWT output without explicitly reconstructing
* the entire sorted rotations matrix.
* </p>
*
* <p>The algorithm works by:
* <ol>
* <li>Creating the first column by sorting the BWT string</li>
* <li>Building a mapping from first column indices to last column indices</li>
* <li>Following this mapping starting from the original index to reconstruct the string</li>
* </ol>
* </p>
*
* @param bwtString the transformed string (L-column) from the forward transform; must not be {@code null}
* @param originalIndex the index of the original string row from the forward transform;
* use -1 for empty strings
* @return the original, untransformed string; returns empty string if input is empty or {@code originalIndex} is -1
* @throws NullPointerException if {@code bwtString} is {@code null}
* @throws IllegalArgumentException if {@code originalIndex} is out of valid range (except -1)
*/
public static String inverseTransform(String bwtString, int originalIndex) {
if (bwtString == null || bwtString.isEmpty() || originalIndex == -1) {
return "";
}
int n = bwtString.length();
if (originalIndex < 0 || originalIndex >= n) {
throw new IllegalArgumentException("Original index must be between 0 and " + (n - 1) + ", got: " + originalIndex);
}
char[] lastColumn = bwtString.toCharArray();
char[] firstColumn = bwtString.toCharArray();
Arrays.sort(firstColumn);
// Create the "next" array for LF-mapping.
// next[i] stores the row index in the last column that corresponds to firstColumn[i]
int[] next = new int[n];
// Track the count of each character seen so far in the last column
Map<Character, Integer> countMap = new HashMap<>();
// Store the first occurrence index of each character in the first column
Map<Character, Integer> firstOccurrence = new HashMap<>();
for (int i = 0; i < n; i++) {
if (!firstOccurrence.containsKey(firstColumn[i])) {
firstOccurrence.put(firstColumn[i], i);
}
}
// Build the LF-mapping
for (int i = 0; i < n; i++) {
char c = lastColumn[i];
int count = countMap.getOrDefault(c, 0);
int firstIndex = firstOccurrence.get(c);
next[firstIndex + count] = i;
countMap.put(c, count + 1);
}
// Reconstruct the original string by following the LF-mapping
StringBuilder originalString = new StringBuilder(n);
int currentRow = originalIndex;
for (int i = 0; i < n; i++) {
originalString.append(firstColumn[currentRow]);
currentRow = next[currentRow];
}
return originalString.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/MoveToFront.java | src/main/java/com/thealgorithms/compression/MoveToFront.java | package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
/**
* Implementation of the Move-to-Front (MTF) transform and its inverse.
* <p>
* MTF is a data transformation algorithm that encodes each symbol in the input
* as its current position in a dynamically-maintained list, then moves that symbol
* to the front of the list. This transformation is particularly effective when used
* after the Burrows-Wheeler Transform (BWT), as BWT groups similar characters together.
* </p>
*
* <p>The transform converts runs of repeated characters into sequences of small integers
* (often zeros), which are highly compressible by subsequent entropy encoding algorithms
* like Run-Length Encoding (RLE) or Huffman coding. This technique is used in the
* bzip2 compression algorithm.
* </p>
*
* <p><b>How it works:</b>
* <ol>
* <li>Maintain a list of symbols (the alphabet), initially in a fixed order</li>
* <li>For each input symbol:
* <ul>
* <li>Output its current index in the list</li>
* <li>Move that symbol to the front of the list</li>
* </ul>
* </li>
* </ol>
* This means frequently occurring symbols quickly move to the front and are encoded
* with small indices (often 0), while rare symbols remain near the back.
* </p>
*
* <p><b>Time Complexity:</b>
* <ul>
* <li>Forward transform: O(n × m) where n is input length and m is alphabet size</li>
* <li>Inverse transform: O(n × m)</li>
* </ul>
* Note: Using {@link LinkedList} for O(1) insertions and O(m) search operations.
* </p>
*
* <p><b>Example:</b></p>
* <pre>
* Input: "annb$aa"
* Alphabet: "$abn" (initial order)
* Output: [1, 3, 0, 3, 3, 3, 0]
*
* Step-by-step:
* - 'a': index 1 in [$,a,b,n] → output 1, list becomes [a,$,b,n]
* - 'n': index 3 in [a,$,b,n] → output 3, list becomes [n,a,$,b]
* - 'n': index 0 in [n,a,$,b] → output 0, list stays [n,a,$,b]
* - 'b': index 3 in [n,a,$,b] → output 3, list becomes [b,n,a,$]
* - etc.
*
* Notice how repeated 'n' characters produce zeros after the first occurrence!
* </pre>
*
* @see <a href="https://en.wikipedia.org/wiki/Move-to-front_transform">Move-to-front transform (Wikipedia)</a>
*/
public final class MoveToFront {
private MoveToFront() {
}
/**
* Performs the forward Move-to-Front transform.
* <p>
* Converts the input string into a list of integers, where each integer represents
* the position of the corresponding character in a dynamically-maintained alphabet list.
* </p>
*
* <p><b>Note:</b> All characters in the input text must exist in the provided alphabet,
* otherwise an {@link IllegalArgumentException} is thrown. The alphabet should contain
* all unique characters that may appear in the input.</p>
*
* @param text the input string to transform; if empty, returns an empty list
* @param initialAlphabet a string containing the initial ordered set of symbols
* (e.g., "$abn" or the full ASCII set); must not be empty
* when {@code text} is non-empty
* @return a list of integers representing the transformed data, where each integer
* is the index of the corresponding input character in the current alphabet state
* @throws IllegalArgumentException if {@code text} is non-empty and {@code initialAlphabet}
* is {@code null} or empty
* @throws IllegalArgumentException if any character in {@code text} is not found in
* {@code initialAlphabet}
*/
public static List<Integer> transform(String text, String initialAlphabet) {
if (text == null || text.isEmpty()) {
return new ArrayList<>();
}
if (initialAlphabet == null || initialAlphabet.isEmpty()) {
throw new IllegalArgumentException("Alphabet cannot be null or empty when text is not empty.");
}
List<Integer> output = new ArrayList<>(text.length());
// Use LinkedList for O(1) add-to-front and O(n) remove operations
// This is more efficient than ArrayList for the move-to-front pattern
List<Character> alphabet = initialAlphabet.chars().mapToObj(c -> (char) c).collect(Collectors.toCollection(LinkedList::new));
for (char c : text.toCharArray()) {
int index = alphabet.indexOf(c);
if (index == -1) {
throw new IllegalArgumentException("Symbol '" + c + "' not found in the initial alphabet.");
}
output.add(index);
// Move the character to the front
Character symbol = alphabet.remove(index);
alphabet.addFirst(symbol);
}
return output;
}
/**
* Performs the inverse Move-to-Front transform.
* <p>
* Reconstructs the original string from the list of indices produced by the
* forward transform. This requires the exact same initial alphabet that was
* used in the forward transform.
* </p>
*
* <p><b>Important:</b> The {@code initialAlphabet} parameter must be identical
* to the one used in the forward transform, including character order, or the
* output will be incorrect.</p>
*
* @param indices The list of integers from the forward transform.
* @param initialAlphabet the exact same initial alphabet string used for the forward transform;
* if {@code null} or empty, returns an empty string
* @return the original, untransformed string
* @throws IllegalArgumentException if any index in {@code indices} is negative or
* exceeds the current alphabet size
*/
public static String inverseTransform(Collection<Integer> indices, String initialAlphabet) {
if (indices == null || indices.isEmpty() || initialAlphabet == null || initialAlphabet.isEmpty()) {
return "";
}
StringBuilder output = new StringBuilder(indices.size());
// Use LinkedList for O(1) add-to-front and O(n) remove operations
List<Character> alphabet = initialAlphabet.chars().mapToObj(c -> (char) c).collect(Collectors.toCollection(LinkedList::new));
for (int index : indices) {
if (index < 0 || index >= alphabet.size()) {
throw new IllegalArgumentException("Index " + index + " is out of bounds for the current alphabet of size " + alphabet.size() + ".");
}
// Get the symbol at the index
char symbol = alphabet.get(index);
output.append(symbol);
// Move the symbol to the front (mirroring the forward transform)
alphabet.remove(index);
alphabet.addFirst(symbol);
}
return output.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/compression/LZW.java | src/main/java/com/thealgorithms/compression/LZW.java | package com.thealgorithms.compression;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An implementation of the Lempel-Ziv-Welch (LZW) algorithm.
*
* <p>
* LZW is a universal lossless data compression algorithm created by Abraham
* Lempel, Jacob Ziv, and Terry Welch. It works by building a dictionary of
* strings encountered during compression and replacing occurrences of those
* strings with a shorter code.
* </p>
*
* <p>
* This implementation handles standard ASCII characters and provides methods for
* both compression and decompression.
* <ul>
* <li>Compressing "TOBEORNOTTOBEORTOBEORNOT" results in a list of integer
* codes.</li>
* <li>Decompressing that list of codes results back in the original
* string.</li>
* </ul>
* </p>
*
* <p>
* Time Complexity: O(n) for both compression and decompression, where n is the
* length of the input string.
* </p>
*
* <p>
* References:
* <ul>
* <li><a href="https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch">Wikipedia:
* Lempel–Ziv–Welch</a></li>
* </ul>
* </p>
*/
public final class LZW {
/**
* Private constructor to prevent instantiation of this utility class.
*/
private LZW() {
}
/**
* Compresses a string using the LZW algorithm.
*
* @param uncompressed The string to be compressed. Can be null.
* @return A list of integers representing the compressed data. Returns an empty
* list if the input is null or empty.
*/
public static List<Integer> compress(String uncompressed) {
if (uncompressed == null || uncompressed.isEmpty()) {
return new ArrayList<>();
}
// Initialize dictionary with single characters (ASCII 0-255)
int dictSize = 256;
Map<String, Integer> dictionary = new HashMap<>();
for (int i = 0; i < dictSize; i++) {
dictionary.put("" + (char) i, i);
}
String w = "";
List<Integer> result = new ArrayList<>();
for (char c : uncompressed.toCharArray()) {
String wc = w + c;
if (dictionary.containsKey(wc)) {
// If the new string is in the dictionary, extend the current string
w = wc;
} else {
// Otherwise, output the code for the current string
result.add(dictionary.get(w));
// Add the new string to the dictionary
dictionary.put(wc, dictSize++);
// Start a new current string
w = "" + c;
}
}
// Output the code for the last remaining string
result.add(dictionary.get(w));
return result;
}
/**
* Decompresses a list of integers back into a string using the LZW algorithm.
*
* @param compressed A list of integers representing the compressed data. Can be
* null.
* @return The original, uncompressed string. Returns an empty string if the
* input is null or empty.
*/
public static String decompress(List<Integer> compressed) {
if (compressed == null || compressed.isEmpty()) {
return "";
}
// Initialize dictionary with single characters (ASCII 0-255)
int dictSize = 256;
Map<Integer, String> dictionary = new HashMap<>();
for (int i = 0; i < dictSize; i++) {
dictionary.put(i, "" + (char) i);
}
// Decompress the first code
String w = "" + (char) (int) compressed.removeFirst();
StringBuilder result = new StringBuilder(w);
for (int k : compressed) {
String entry;
if (dictionary.containsKey(k)) {
// The code is in the dictionary
entry = dictionary.get(k);
} else if (k == dictSize) {
// Special case for sequences like "ababab"
entry = w + w.charAt(0);
} else {
throw new IllegalArgumentException("Bad compressed k: " + k);
}
result.append(entry);
// Add new sequence to the dictionary
dictionary.put(dictSize++, w + entry.charAt(0));
w = entry;
}
return result.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/Node.java | src/main/java/com/thealgorithms/datastructures/Node.java | package com.thealgorithms.datastructures;
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private final T value;
private final List<Node<T>> children;
public Node(final T value) {
this.value = value;
this.children = new ArrayList<>();
}
public Node(final T value, final List<Node<T>> children) {
this.value = value;
this.children = children;
}
public T getValue() {
return value;
}
public void addChild(Node<T> child) {
children.add(child);
}
public List<Node<T>> getChildren() {
return children;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java | src/main/java/com/thealgorithms/datastructures/disjointsetunion/Node.java | package com.thealgorithms.datastructures.disjointsetunion;
public class Node<T> {
/**
* The rank of the node, used for optimizing union operations.
*/
public int rank;
/**
* Reference to the parent node in the set.
* Initially, a node is its own parent (represents a singleton set).
*/
public Node<T> parent;
/**
* The data element associated with the node.
*/
public T data;
public Node(final T data) {
this.data = data;
parent = this; // Initially, a node is its own parent.
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnion.java | src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnion.java | package com.thealgorithms.datastructures.disjointsetunion;
/**
* Disjoint Set Union (DSU), also known as Union-Find, is a data structure that tracks a set of elements
* partitioned into disjoint (non-overlapping) subsets. It supports two primary operations efficiently:
*
* <ul>
* <li>Find: Determine which subset a particular element belongs to.</li>
* <li>Union: Merge two subsets into a single subset.</li>
* </ul>
*
* @see <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure">Disjoint Set Union (Wikipedia)</a>
*/
public class DisjointSetUnion<T> {
/**
* Creates a new disjoint set containing the single specified element.
*
* @param value the element to be placed in a new singleton set
* @return a node representing the new set
*/
public Node<T> makeSet(final T value) {
return new Node<>(value);
}
/**
* Finds and returns the representative (root) of the set containing the given node.
* This method applies path compression to flatten the tree structure for future efficiency.
*
* @param node the node whose set representative is to be found
* @return the representative (root) node of the set
*/
public Node<T> findSet(Node<T> node) {
if (node != node.parent) {
node.parent = findSet(node.parent);
}
return node.parent;
}
/**
* Merges the sets containing the two given nodes. Union by rank is used to attach the smaller tree under the larger one.
* If both sets have the same rank, one becomes the parent and its rank is incremented.
*
* @param x a node in the first set
* @param y a node in the second set
*/
public void unionSets(Node<T> x, Node<T> y) {
Node<T> rootX = findSet(x);
Node<T> rootY = findSet(y);
if (rootX == rootY) {
return; // They are already in the same set
}
// Merging happens based on rank of node, this is done to avoid long chaining of nodes and reduce time
// to find root of the component. Idea is to attach small components in big, instead of other way around.
if (rootX.rank > rootY.rank) {
rootY.parent = rootX;
} else if (rootY.rank > rootX.rank) {
rootX.parent = rootY;
} else {
rootY.parent = rootX;
rootX.rank++;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java | src/main/java/com/thealgorithms/datastructures/disjointsetunion/DisjointSetUnionBySize.java | package com.thealgorithms.datastructures.disjointsetunion;
/**
* Disjoint Set Union (DSU) with Union by Size.
* This data structure tracks a set of elements partitioned into disjoint (non-overlapping) subsets.
* It supports two primary operations efficiently:
*
* <ul>
* <li>Find: Determine which subset a particular element belongs to.</li>
* <li>Union: Merge two subsets into a single subset using union by size.</li>
* </ul>
*
* Union by size always attaches the smaller tree under the root of the larger tree.
* This helps keep the tree shallow, improving the efficiency of find operations.
*
* @see <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure">Disjoint Set Union (Wikipedia)</a>
*/
public class DisjointSetUnionBySize<T> {
/**
* Node class for DSU by size.
* Each node keeps track of its parent and the size of the set it represents.
*/
public static class Node<T> {
public T value;
public Node<T> parent;
public int size; // size of the set
public Node(T value) {
this.value = value;
this.parent = this;
this.size = 1; // initially, the set size is 1
}
}
/**
* Creates a new disjoint set containing the single specified element.
* @param value the element to be placed in a new singleton set
* @return a node representing the new set
*/
public Node<T> makeSet(final T value) {
return new Node<>(value);
}
/**
* Finds and returns the representative (root) of the set containing the given node.
* This method applies path compression to flatten the tree structure for future efficiency.
* @param node the node whose set representative is to be found
* @return the representative (root) node of the set
*/
public Node<T> findSet(Node<T> node) {
if (node != node.parent) {
node.parent = findSet(node.parent); // path compression
}
return node.parent;
}
/**
* Merges the sets containing the two given nodes using union by size.
* The root of the smaller set is attached to the root of the larger set.
* @param x a node in the first set
* @param y a node in the second set
*/
public void unionSets(Node<T> x, Node<T> y) {
Node<T> rootX = findSet(x);
Node<T> rootY = findSet(y);
if (rootX == rootY) {
return; // They are already in the same set
}
// Union by size: attach smaller tree under the larger one
if (rootX.size < rootY.size) {
rootX.parent = rootY;
rootY.size += rootX.size; // update size
} else {
rootY.parent = rootX;
rootX.size += rootY.size; // update size
}
}
}
// This implementation uses union by size instead of union by rank.
// The size field tracks the number of elements in each set.
// When two sets are merged, the smaller set is always attached to the larger set's root.
// This helps keep the tree shallow and improves the efficiency of find operations.
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/QuickSortLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/QuickSortLinkedList.java | package com.thealgorithms.datastructures.lists;
/*
*
* @aurthor - Prabhat-Kumar-42
* @github - https://github.com/Prabhat-Kumar-42
*
* Problem :
* QuickSort on Linked List
*
* Note: Taking head as pivot in current implementation.
* N represents NULL node
* Example:
*
* -> Given Linked List :
* 5 -> 3 -> 8 -> 1 -> 10 -> 2 -> 7 -> 4 -> 9 -> 6
*
* -> How Sorting will work according to the QuickSort Algo written below
*
* current pivot : 5
* List lessThanPivot : 3 -> 1 -> 2 -> 4
* List greaterThanPivot : 5 -> 8 -> 10 -> 7 -> 9 -> 6
*
* -> reccur for lessThanPivot and greaterThanPivot
*
* lessThanPivot :
* current pivot : 3
* lessThanPivot : 1 -> 2
* greaterThanPivot : 4
*
* greaterThanPivot:
* current pivot : 5
* lessThanPivot : null
* greaterThanPivot : 8 -> 10 -> 7 -> 9 -> 6
*
* By following the above pattern, reccuring tree will form like below :
*
* List-> 5 -> 3 -> 8 -> 1 -> 10 -> 2 -> 7 -> 4 -> 9 -> 6
*
* Pivot : 5
* /\
* / \
* / \
* / \
* / \
* List: (3 -> 1 -> 2 -> 4) (5 -> 8 -> 10 -> 7 -> 9 -> 6)
* Pivot : 3 5
* /\ /\
* / \ / \
* / \ / \
* / \ / \
* List: (1 -> 2) (4) (N) (8 -> 10 -> 7 -> 9 -> 6)
* Pivot: 1 4 8
* /\ /\ /\
* / \ / \ / \
* / \ / \ / \
* List: (N) (2) (N) (N) (6 -> 7) (9 -> 10)
* Pivot: 2 6 9
* /\ /\ /\
* / \ / \ / \
* / \ / \ / \
* List: (N) (N) (N) (7) (N) (10)
* Pivot: 7 10
* /\ /\
* / \ / \
* / \ / \
* (N) (N) (N) (N)
*
*
* -> After this the tree will reccur back (or backtrack)
* and the returning list from left and right subtree will attach
* themselves around pivot.
* i.e. ,
* (listFromLeftSubTree) -> (Pivot) -> (listFromRightSubtree)
*
* This will continue until whole list is merged back
*
* eg :
* Megring the above Tree back we get :
*
* List: (1 -> 2) (4) (6 -> 7) (9 -> 10)
* \ / \ /
* \ / \ /
* \ / \ /
* \ / \ /
* \ / \ /
* \ / \ /
* \ / \ /
* Pivot: 3 8
* List: (1 -> 2 -> 3 -> 4) (6 -> 7 -> 8 -> 9 -> 10)
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* \ /
* \/
* Pivot: 5
* List: (1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> 10)
*
*
* -> This will result in a sorted Linked List
*/
public class QuickSortLinkedList {
private final SinglyLinkedList list; // The linked list to be sorted
private SinglyLinkedListNode head; // Head of the list
/**
* Constructor that initializes the QuickSortLinkedList with a given linked list.
*
* @param list The singly linked list to be sorted
*/
public QuickSortLinkedList(SinglyLinkedList list) {
this.list = list;
this.head = list.getHead();
}
/**
* Sorts the linked list using the QuickSort algorithm.
* The sorted list replaces the original list within the SinglyLinkedList instance.
*/
public void sortList() {
head = sortList(head);
list.setHead(head);
}
/**
* Recursively sorts a linked list by partitioning it around a pivot element.
*
* <p>Each recursive call selects a pivot, partitions the list into elements less
* than the pivot and elements greater than or equal to the pivot, then combines
* the sorted sublists around the pivot.</p>
*
* @param head The head node of the list to sort
* @return The head node of the sorted linked list
*/
private SinglyLinkedListNode sortList(SinglyLinkedListNode head) {
if (head == null || head.next == null) {
return head;
}
SinglyLinkedListNode pivot = head;
head = head.next;
pivot.next = null;
SinglyLinkedListNode lessHead = new SinglyLinkedListNode();
SinglyLinkedListNode lessTail = lessHead;
SinglyLinkedListNode greaterHead = new SinglyLinkedListNode();
SinglyLinkedListNode greaterTail = greaterHead;
while (head != null) {
if (head.value < pivot.value) {
lessTail.next = head;
lessTail = lessTail.next;
} else {
greaterTail.next = head;
greaterTail = greaterTail.next;
}
head = head.next;
}
lessTail.next = null;
greaterTail.next = null;
SinglyLinkedListNode sortedLess = sortList(lessHead.next);
SinglyLinkedListNode sortedGreater = sortList(greaterHead.next);
if (sortedLess == null) {
pivot.next = sortedGreater;
return pivot;
} else {
SinglyLinkedListNode current = sortedLess;
while (current.next != null) {
current = current.next;
}
current.next = pivot;
pivot.next = sortedGreater;
return sortedLess;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/CursorLinkedList.java | package com.thealgorithms.datastructures.lists;
import java.util.Objects;
/**
* CursorLinkedList is an array-based implementation of a singly linked list.
* Each node in the array simulates a linked list node, storing an element and
* the index of the next node. This structure allows for efficient list operations
* without relying on traditional pointers.
*
* @param <T> the type of elements in this list
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class CursorLinkedList<T> {
/**
* Node represents an individual element in the list, containing the element
* itself and a pointer (index) to the next node.
*/
private static class Node<T> {
T element;
int next;
Node(T element, int next) {
this.element = element;
this.next = next;
}
}
private final int os;
private int head;
private final Node<T>[] cursorSpace;
private int count;
private static final int CURSOR_SPACE_SIZE = 100;
{
// Initialize cursor space array and free list pointers
cursorSpace = new Node[CURSOR_SPACE_SIZE];
for (int i = 0; i < CURSOR_SPACE_SIZE; i++) {
cursorSpace[i] = new Node<>(null, i + 1);
}
cursorSpace[CURSOR_SPACE_SIZE - 1].next = 0;
}
/**
* Constructs an empty CursorLinkedList with the default capacity.
*/
public CursorLinkedList() {
os = 0;
count = 0;
head = -1;
}
/**
* Prints all elements in the list in their current order.
*/
public void printList() {
if (head != -1) {
int start = head;
while (start != -1) {
T element = cursorSpace[start].element;
System.out.println(element.toString());
start = cursorSpace[start].next;
}
}
}
/**
* Finds the logical index of a specified element in the list.
*
* @param element the element to search for in the list
* @return the logical index of the element, or -1 if not found
* @throws NullPointerException if element is null
*/
public int indexOf(T element) {
if (element == null) {
throw new NullPointerException("Element cannot be null");
}
try {
Objects.requireNonNull(element);
Node<T> iterator = cursorSpace[head];
for (int i = 0; i < count; i++) {
if (iterator.element.equals(element)) {
return i;
}
iterator = cursorSpace[iterator.next];
}
} catch (Exception e) {
return -1;
}
return -1;
}
/**
* Retrieves an element at a specified logical index in the list.
*
* @param position the logical index of the element
* @return the element at the specified position, or null if index is out of bounds
*/
public T get(int position) {
if (position >= 0 && position < count) {
int start = head;
int counter = 0;
while (start != -1) {
T element = cursorSpace[start].element;
if (counter == position) {
return element;
}
start = cursorSpace[start].next;
counter++;
}
}
return null;
}
/**
* Removes the element at a specified logical index from the list.
*
* @param index the logical index of the element to remove
*/
public void removeByIndex(int index) {
if (index >= 0 && index < count) {
T element = get(index);
remove(element);
}
}
/**
* Removes a specified element from the list.
*
* @param element the element to be removed
* @throws NullPointerException if element is null
*/
public void remove(T element) {
Objects.requireNonNull(element);
T tempElement = cursorSpace[head].element;
int tempNext = cursorSpace[head].next;
if (tempElement.equals(element)) {
free(head);
head = tempNext;
} else {
int prevIndex = head;
int currentIndex = cursorSpace[prevIndex].next;
while (currentIndex != -1) {
T currentElement = cursorSpace[currentIndex].element;
if (currentElement.equals(element)) {
cursorSpace[prevIndex].next = cursorSpace[currentIndex].next;
free(currentIndex);
break;
}
prevIndex = currentIndex;
currentIndex = cursorSpace[prevIndex].next;
}
}
count--;
}
/**
* Allocates a new node index for storing an element.
*
* @return the index of the newly allocated node
* @throws OutOfMemoryError if no space is available in cursor space
*/
private int alloc() {
int availableNodeIndex = cursorSpace[os].next;
if (availableNodeIndex == 0) {
throw new OutOfMemoryError();
}
cursorSpace[os].next = cursorSpace[availableNodeIndex].next;
cursorSpace[availableNodeIndex].next = -1;
return availableNodeIndex;
}
/**
* Releases a node back to the free list.
*
* @param index the index of the node to release
*/
private void free(int index) {
Node<T> osNode = cursorSpace[os];
int osNext = osNode.next;
cursorSpace[os].next = index;
cursorSpace[index].element = null;
cursorSpace[index].next = osNext;
}
/**
* Appends an element to the end of the list.
*
* @param element the element to append
* @throws NullPointerException if element is null
*/
public void append(T element) {
Objects.requireNonNull(element);
int availableIndex = alloc();
cursorSpace[availableIndex].element = element;
if (head == -1) {
head = availableIndex;
} else {
int iterator = head;
while (cursorSpace[iterator].next != -1) {
iterator = cursorSpace[iterator].next;
}
cursorSpace[iterator].next = availableIndex;
}
cursorSpace[availableIndex].next = -1;
count++;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/CircularDoublyLinkedList.java | package com.thealgorithms.datastructures.lists;
/**
* This class is a circular doubly linked list implementation. In a circular
* doubly linked list,
* the last node points back to the first node and the first node points back to
* the last node,
* creating a circular chain in both directions.
*
* 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 <E> the type of elements held in this list
*/
public class CircularDoublyLinkedList<E> {
static final class Node<E> {
Node<E> next;
Node<E> prev;
E value;
private Node(E value, Node<E> next, Node<E> prev) {
this.value = value;
this.next = next;
this.prev = prev;
}
}
private int size;
Node<E> head = null;
/**
* Initializes a new circular doubly linked list. A dummy head node is used for
* simplicity,
* pointing initially to itself to ensure the list is never empty.
*/
public CircularDoublyLinkedList() {
head = new Node<>(null, null, null);
head.next = head;
head.prev = head;
size = 0;
}
/**
* Returns the current size of the list.
*
* @return the number of elements in the list
*/
public int getSize() {
return size;
}
/**
* Appends a new element to the end of the list. Throws a NullPointerException
* if
* a null value is provided.
*
* @param value the value to append to the list
* @throws NullPointerException if the value is null
*/
public void append(E value) {
if (value == null) {
throw new NullPointerException("Cannot add null element to the list");
}
Node<E> newNode = new Node<>(value, head, head.prev);
head.prev.next = newNode;
head.prev = newNode;
size++;
}
/**
* Returns a string representation of the list in the format "[ element1,
* element2, ... ]".
* An empty list is represented as "[]".
*
* @return the string representation of the list
*/
public String toString() {
if (size == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder("[ ");
Node<E> current = head.next;
while (current != head) {
sb.append(current.value);
if (current.next != head) {
sb.append(", ");
}
current = current.next;
}
sb.append(" ]");
return sb.toString();
}
/**
* Removes and returns the element at the specified position in the list.
* Throws an IndexOutOfBoundsException if the position is invalid.
*
* @param pos the position of the element to remove
* @return the value of the removed element - pop operation
* @throws IndexOutOfBoundsException if the position is out of range
*/
public E remove(int pos) {
if (pos >= size || pos < 0) {
throw new IndexOutOfBoundsException("Position out of bounds");
}
Node<E> current = head.next;
for (int i = 0; i < pos; i++) {
current = current.next;
}
current.prev.next = current.next;
current.next.prev = current.prev;
E removedValue = current.value;
size--;
return removedValue;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java | src/main/java/com/thealgorithms/datastructures/lists/MergeSortedArrayList.java | package com.thealgorithms.datastructures.lists;
import java.util.Collection;
import java.util.List;
/**
* Utility class for merging two sorted ArrayLists of integers into a single sorted collection.
*
* <p>This class provides a static `merge` method to combine two pre-sorted lists of integers into a
* single sorted list. It does so without modifying the input lists by adding elements from both lists in sorted order
* into the result list.</p>
*
* <p>Example usage:</p>
* <pre>
* List<Integer> listA = Arrays.asList(1, 3, 5, 7, 9);
* List<Integer> listB = Arrays.asList(2, 4, 6, 8, 10);
* List<Integer> result = new ArrayList<>();
* MergeSortedArrayList.merge(listA, listB, result);
* </pre>
*
* <p>The resulting `result` list will be [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].</p>
*
* <p>Note: This class cannot be instantiated as it is designed to be used only with its static `merge` method.</p>
*
* <p>This implementation assumes the input lists are already sorted in ascending order.</p>
*
* @author https://github.com/shellhub
* @see List
*/
public final class MergeSortedArrayList {
private MergeSortedArrayList() {
}
/**
* Merges two sorted lists of integers into a single sorted collection.
*
* <p>This method does not alter the original lists (`listA` and `listB`). Instead, it inserts elements from both
* lists into `listC` in a way that maintains ascending order.</p>
*
* @param listA The first sorted list of integers.
* @param listB The second sorted list of integers.
* @param listC The collection to hold the merged result, maintaining sorted order.
* @throws NullPointerException if any of the input lists or result collection is null.
*/
public static void merge(List<Integer> listA, List<Integer> listB, Collection<Integer> listC) {
if (listA == null || listB == null || listC == null) {
throw new NullPointerException("Input lists and result collection must not be null.");
}
int pa = 0;
int pb = 0;
while (pa < listA.size() && pb < listB.size()) {
if (listA.get(pa) <= listB.get(pb)) {
listC.add(listA.get(pa++));
} else {
listC.add(listB.get(pb++));
}
}
// Add remaining elements from listA, if any
while (pa < listA.size()) {
listC.add(listA.get(pa++));
}
// Add remaining elements from listB, if any
while (pb < listB.size()) {
listC.add(listB.get(pb++));
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java | src/main/java/com/thealgorithms/datastructures/lists/ReverseKGroup.java | package com.thealgorithms.datastructures.lists;
/**
* The ReverseKGroup class provides functionality to reverse nodes in a
* linked list in groups of k nodes.
* <p>
* This algorithm follows the approach of reversing the linked list in segments of
* size k. If the remaining nodes are fewer than k, they remain unchanged.
* </p>
* <p>
* Example:
* Given a linked list: 1 -> 2 -> 3 -> 4 -> 5 and k = 3,
* the output will be: 3 -> 2 -> 1 -> 4 -> 5.
* </p>
* <p>
* The implementation contains:
* - {@code length(SinglyLinkedListNode head)}: A method to calculate the length of the linked list.
* - {@code reverse(SinglyLinkedListNode head, int count, int k)}: A helper method that reverses the nodes
* in the linked list in groups of k.
* - {@code reverseKGroup(SinglyLinkedListNode head, int k)}: The main method that initiates the reversal
* process by calling the reverse method.
* </p>
* <p>
* Complexity:
* <ul>
* <li>Time Complexity: O(n), where n is the number of nodes in the linked list.</li>
* <li>Space Complexity: O(1), as we are reversing in place.</li>
* </ul>
* </p>
*
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class ReverseKGroup {
/**
* Calculates the length of the linked list.
*
* @param head The head node of the linked list.
* @return The total number of nodes in the linked list.
*/
public int length(SinglyLinkedListNode head) {
SinglyLinkedListNode curr = head;
int count = 0;
while (curr != null) {
curr = curr.next;
count++;
}
return count;
}
/**
* Reverses the linked list in groups of k nodes.
*
* @param head The head node of the linked list.
* @param count The remaining number of nodes.
* @param k The size of the group to reverse.
* @return The new head of the reversed linked list segment.
*/
public SinglyLinkedListNode reverse(SinglyLinkedListNode head, int count, int k) {
if (count < k) {
return head;
}
SinglyLinkedListNode prev = null;
int count1 = 0;
SinglyLinkedListNode curr = head;
SinglyLinkedListNode next = null;
while (curr != null && count1 < k) {
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count1++;
}
if (next != null) {
head.next = reverse(next, count - k, k);
}
return prev;
}
/**
* Reverses the linked list in groups of k nodes.
*
* @param head The head node of the linked list.
* @param k The size of the group to reverse.
* @return The head of the modified linked list after reversal.
*/
public SinglyLinkedListNode reverseKGroup(SinglyLinkedListNode head, int k) {
int count = length(head);
return reverse(head, count, k);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/MergeKSortedLinkedList.java | package com.thealgorithms.datastructures.lists;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* The MergeKSortedLinkedList class provides a method to merge multiple sorted linked lists
* into a single sorted linked list.
* This implementation uses a min-heap (priority queue) to efficiently
* find the smallest node across all lists, thus optimizing the merge process.
*
* <p>Example usage:
* <pre>
* Node list1 = new Node(1, new Node(4, new Node(5)));
* Node list2 = new Node(1, new Node(3, new Node(4)));
* Node list3 = new Node(2, new Node(6));
* Node[] lists = { list1, list2, list3 };
*
* MergeKSortedLinkedList merger = new MergeKSortedLinkedList();
* Node mergedHead = merger.mergeKList(lists, lists.length);
* </pre>
* </p>
*
* <p>This class is designed to handle nodes of integer linked lists and can be expanded for additional data types if needed.</p>
*
* @author Arun Pandey (https://github.com/pandeyarun709)
*/
public class MergeKSortedLinkedList {
/**
* Merges K sorted linked lists into a single sorted linked list.
*
* <p>This method uses a priority queue (min-heap) to repeatedly extract the smallest node from the heads of all the lists,
* then inserts the next node from that list into the heap. The process continues until all nodes have been processed,
* resulting in a fully merged and sorted linked list.</p>
*
* @param a Array of linked list heads to be merged.
* @param n Number of linked lists.
* @return Head of the merged sorted linked list.
*/
Node mergeKList(Node[] a, int n) {
if (a == null || n == 0) {
return null;
}
// Min Heap to store nodes based on their values for efficient retrieval of the smallest element.
PriorityQueue<Node> minHeap = new PriorityQueue<>(Comparator.comparingInt(x -> x.data));
// Initialize the min-heap with the head of each non-null linked list
for (Node node : a) {
if (node != null) {
minHeap.add(node);
}
}
// Start merging process
Node head = minHeap.poll(); // Smallest head is the initial head of the merged list
if (head != null && head.next != null) {
minHeap.add(head.next);
}
Node curr = head;
while (!minHeap.isEmpty()) {
Node temp = minHeap.poll();
curr.next = temp;
curr = temp;
// Add the next node in the current list to the heap if it exists
if (temp.next != null) {
minHeap.add(temp.next);
}
}
return head;
}
/**
* Represents a node in the linked list.
*/
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
Node(int data, Node next) {
this.data = data;
this.next = next;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java | src/main/java/com/thealgorithms/datastructures/lists/RandomNode.java | package com.thealgorithms.datastructures.lists;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* @author <a href="https://github.com/skmodi649">Suraj Kumar</a>
* <p>
* PROBLEM DESCRIPTION :
* There is a single linked list and we are supposed to find a random node in the given linked list
* <p>
* ALGORITHM :
* Step 1 : START
* Step 2 : Create an arraylist of type integer
* Step 3 : Declare an integer type variable for size and linked list type for head
* Step 4 : We will use two methods, one for traversing through the linked list using while loop and
* also increase the size by 1
* <p>
* (a) RandomNode(head)
* (b) run a while loop till null;
* (c) add the value to arraylist;
* (d) increase the size;
* <p>
* Step 5 : Now use another method for getting random values using Math.random() and return the
* value present in arraylist for the calculated index Step 6 : Now in main() method we will simply
* insert nodes in the linked list and then call the appropriate method and then print the random
* node generated Step 7 : STOP
*/
public class RandomNode {
private final List<Integer> list;
private int size;
private static final Random RAND = new Random();
static class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public RandomNode(ListNode head) {
list = new ArrayList<>();
ListNode temp = head;
// Now using while loop to traverse through the linked list and
// go on adding values and increasing the size value by 1
while (temp != null) {
list.add(temp.val);
temp = temp.next;
size++;
}
}
public int getRandom() {
int index = RAND.nextInt(size);
return list.get(index);
}
/**
* OUTPUT :
* First output :
* Random Node : 25
* Second output :
* Random Node : 78
* Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
* Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
* Time Complexity : O(n)
* Auxiliary Space Complexity : O(1)
*/
// Driver program to test above functions
public static void main(String[] args) {
ListNode head = new ListNode(15);
head.next = new ListNode(25);
head.next.next = new ListNode(4);
head.next.next.next = new ListNode(1);
head.next.next.next.next = new ListNode(78);
head.next.next.next.next.next = new ListNode(63);
RandomNode list = new RandomNode(head);
int randomNum = list.getRandom();
System.out.println("Random Node : " + randomNum);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java | src/main/java/com/thealgorithms/datastructures/lists/TortoiseHareAlgo.java | package com.thealgorithms.datastructures.lists;
public class TortoiseHareAlgo<E> {
static final class Node<E> {
Node<E> next;
E value;
private Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
private Node<E> head = null;
public TortoiseHareAlgo() {
head = null;
}
public void append(E value) {
Node<E> newNode = new Node<>(value, null);
if (head == null) {
head = newNode;
return;
}
Node<E> current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
public E getMiddle() {
if (head == null) {
return null;
}
Node<E> slow = head;
Node<E> fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow.value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("[");
Node<E> current = head;
while (current != null) {
sb.append(current.value);
if (current.next != null) {
sb.append(", ");
}
current = current.next;
}
sb.append("]");
return sb.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/MergeSortedSinglyLinkedList.java | package com.thealgorithms.datastructures.lists;
/**
* Utility class for merging two sorted singly linked lists.
*
* <p>This class extends the {@link SinglyLinkedList} class to support the merging of two sorted linked lists.
* It provides a static method, `merge`, that takes two sorted singly linked lists, merges them into a single sorted linked list,
* and returns the result.</p>
*
* <p>Example usage:</p>
* <pre>
* SinglyLinkedList listA = new SinglyLinkedList();
* SinglyLinkedList listB = new SinglyLinkedList();
* for (int i = 2; i <= 10; i += 2) {
* listA.insert(i); // listA: 2->4->6->8->10
* listB.insert(i - 1); // listB: 1->3->5->7->9
* }
* SinglyLinkedList mergedList = MergeSortedSinglyLinkedList.merge(listA, listB);
* System.out.println(mergedList); // Output: 1->2->3->4->5->6->7->8->9->10
* </pre>
*
* <p>The `merge` method assumes that both input lists are already sorted in ascending order.
* It returns a new singly linked list that contains all elements from both lists in sorted order.</p>
*
* @see SinglyLinkedList
*/
public class MergeSortedSinglyLinkedList extends SinglyLinkedList {
/**
* Merges two sorted singly linked lists into a single sorted singly linked list.
*
* <p>This method does not modify the input lists; instead, it creates a new merged linked list
* containing all elements from both lists in sorted order.</p>
*
* @param listA The first sorted singly linked list.
* @param listB The second sorted singly linked list.
* @return A new singly linked list containing all elements from both lists in sorted order.
* @throws NullPointerException if either input list is null.
*/
public static SinglyLinkedList merge(SinglyLinkedList listA, SinglyLinkedList listB) {
if (listA == null || listB == null) {
throw new NullPointerException("Input lists must not be null.");
}
SinglyLinkedListNode headA = listA.getHead();
SinglyLinkedListNode headB = listB.getHead();
int size = listA.size() + listB.size();
SinglyLinkedListNode head = new SinglyLinkedListNode();
SinglyLinkedListNode tail = head;
while (headA != null && headB != null) {
if (headA.value <= headB.value) {
tail.next = headA;
headA = headA.next;
} else {
tail.next = headB;
headB = headB.next;
}
tail = tail.next;
}
// Attach remaining nodes
tail.next = (headA == null) ? headB : headA;
return new SinglyLinkedList(head.next, size);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java | src/main/java/com/thealgorithms/datastructures/lists/SearchSinglyLinkedListRecursion.java | package com.thealgorithms.datastructures.lists;
/**
* The SearchSinglyLinkedListRecursion class extends SinglyLinkedList and provides
* a method to search for a value in a singly linked list using recursion.
* <p>
* This class demonstrates a recursive approach to check if a given integer value is
* present in the linked list. The search method calls a private recursive helper method
* `searchRecursion`, which checks each node's value and moves to the next node if necessary.
* </p>
* <p>
* Example:
* Given a list containing the values 1 -> 2 -> 3 -> 4, calling search(3) will return `true`,
* while calling search(5) will return `false`.
* </p>
* <p>
* Complexity:
* <ul>
* <li>Time Complexity: O(n), where n is the number of nodes in the linked list.</li>
* <li>Space Complexity: O(n), due to the recursive call stack in the worst case.</li>
* </ul>
* </p>
*/
public class SearchSinglyLinkedListRecursion extends SinglyLinkedList {
/**
* Recursively searches for a given value in the linked list.
*
* @param node the head node to start the search.
* @param key the integer value to be searched for.
* @return {@code true} if the value `key` is present in the list; otherwise, {@code false}.
*/
private boolean searchRecursion(SinglyLinkedListNode node, int key) {
return (node != null && (node.value == key || searchRecursion(node.next, key)));
}
/**
* Public search method to determine if a key is present in the linked list.
*
* @param key the integer value to be searched for.
* @return {@code true} if the value `key` is present in the list; otherwise, {@code false}.
*/
@Override
public boolean search(int key) {
return searchRecursion(getHead(), key);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedList.java | package com.thealgorithms.datastructures.lists;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.StringJoiner;
/**
* <a href="https://en.wikipedia.org/wiki/Linked_list">wikipedia</a>
*/
public class SinglyLinkedList implements Iterable<Integer> {
/**
* Head refer to the front of the list
*/
private SinglyLinkedListNode head;
/**
* Size of SinglyLinkedList
*/
private int size;
/**
* Init SinglyLinkedList
*/
public SinglyLinkedList() {
head = null;
size = 0;
}
/**
* Init SinglyLinkedList with specified head node and size
*
* @param head the head node of list
* @param size the size of list
*/
public SinglyLinkedList(SinglyLinkedListNode head, int size) {
this.head = head;
this.size = size;
}
/**
* Detects if there is a loop in the singly linked list using floy'd turtle
* and hare algorithm.
*
*/
public boolean detectLoop() {
SinglyLinkedListNode currentNodeFast = head;
SinglyLinkedListNode currentNodeSlow = head;
while (currentNodeFast != null && currentNodeFast.next != null) {
currentNodeFast = currentNodeFast.next.next;
currentNodeSlow = currentNodeSlow.next;
if (currentNodeFast == currentNodeSlow) {
return true;
}
}
return false;
}
/**
* Return the node in the middle of the list
* If the length of the list is even then return item number length/2
* @return middle node of the list
*/
public SinglyLinkedListNode middle() {
if (head == null) {
return null;
}
SinglyLinkedListNode firstCounter = head;
SinglyLinkedListNode secondCounter = firstCounter.next;
while (secondCounter != null && secondCounter.next != null) {
firstCounter = firstCounter.next;
secondCounter = secondCounter.next.next;
}
return firstCounter;
}
/**
* Swaps nodes of two given values a and b.
*
*/
public void swapNodes(int valueFirst, int valueSecond) {
if (valueFirst == valueSecond) {
return;
}
SinglyLinkedListNode previousA = null;
SinglyLinkedListNode currentA = head;
while (currentA != null && currentA.value != valueFirst) {
previousA = currentA;
currentA = currentA.next;
}
SinglyLinkedListNode previousB = null;
SinglyLinkedListNode currentB = head;
while (currentB != null && currentB.value != valueSecond) {
previousB = currentB;
currentB = currentB.next;
}
/* If either of 'a' or 'b' is not present, then return */
if (currentA == null || currentB == null) {
return;
}
// If 'a' is not head node of list
if (previousA != null) {
previousA.next = currentB;
} else {
// make 'b' as the new head
head = currentB;
}
// If 'b' is not head node of list
if (previousB != null) {
previousB.next = currentA;
} else {
// Make 'a' as new head
head = currentA;
}
// Swap next pointer
var temp = currentA.next;
currentA.next = currentB.next;
currentB.next = temp;
}
/**
* Reverse a singly linked list[Iterative] from a given node till the end
*
*/
public SinglyLinkedListNode reverseListIter(SinglyLinkedListNode node) {
SinglyLinkedListNode prev = null;
SinglyLinkedListNode curr = node;
while (curr != null && curr.next != null) {
var next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
// when curr.next==null, the current element is left without pointing it to its prev,so
if (curr != null) {
curr.next = prev;
prev = curr;
}
// prev will be pointing to the last element in the Linkedlist, it will be the new head of
// the reversed linkedlist
return prev;
}
/**
* Reverse a singly linked list[Recursive] from a given node till the end
*
*/
public SinglyLinkedListNode reverseListRec(SinglyLinkedListNode head) {
if (head == null || head.next == null) {
return head;
}
SinglyLinkedListNode prev = null;
SinglyLinkedListNode h2 = reverseListRec(head.next);
head.next.next = head;
head.next = prev;
return h2;
}
/**
* Clear all nodes in the list
*/
public void clear() {
SinglyLinkedListNode cur = head;
while (cur != null) {
cur = cur.next;
}
head = null;
size = 0;
}
/**
* Checks if the list is empty
*
* @return {@code true} if list is empty, otherwise {@code false}.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the size of the linked list.
*
* @return the size of the list.
*/
public int size() {
return size;
}
/**
* Get head of the list.
*
* @return head of the list.
*/
public SinglyLinkedListNode getHead() {
return head;
}
/**
* Set head of the list.
*
*/
public void setHead(SinglyLinkedListNode head) {
this.head = head;
}
/**
* Calculate the count of the list manually
*
* @return count of the list
*/
public int count() {
int count = 0;
for (final var element : this) {
++count;
}
return count;
}
/**
* Test if the value key is present in the list.
*
* @param key the value to be searched.
* @return {@code true} if key is present in the list, otherwise
* {@code false}.
*/
public boolean search(final int key) {
for (final var element : this) {
if (element == key) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner("->");
for (final var element : this) {
joiner.add(element + "");
}
return joiner.toString();
}
public void deleteDuplicates() {
SinglyLinkedListNode pred = head;
// predecessor = the node
// having sublist of its duplicates
SinglyLinkedListNode newHead = head;
while (newHead != null) {
// if it's a beginning of duplicates sublist
// skip all duplicates
if (newHead.next != null && newHead.value == newHead.next.value) {
// move till the end of duplicates sublist
while (newHead.next != null && newHead.value == newHead.next.value) {
newHead = newHead.next;
}
// skip all duplicates
pred.next = newHead.next;
newHead = null;
// otherwise, move predecessor
}
// move forward
pred = pred.next;
newHead = pred;
}
}
public void print() {
SinglyLinkedListNode temp = head;
while (temp != null && temp.next != null) {
System.out.print(temp.value + "->");
temp = temp.next;
}
if (temp != null) {
System.out.print(temp.value);
System.out.println();
}
}
/**
* Inserts an element at the head of the list
*
* @param x element to be added
*/
public void insertHead(int x) {
insertNth(x, 0);
}
/**
* Insert an element at the tail of the list
*
* @param data element to be added
*/
public void insert(int data) {
insertNth(data, size);
}
/**
* Inserts a new node at a specified position of the list
*
* @param data data to be stored in a new node
* @param position position at which a new node is to be inserted
*/
public void insertNth(int data, int position) {
checkBounds(position, 0, size);
SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
if (head == null) {
/* the list is empty */
head = newNode;
size++;
return;
}
if (position == 0) {
/* insert at the head of the list */
newNode.next = head;
head = newNode;
size++;
return;
}
SinglyLinkedListNode cur = head;
for (int i = 0; i < position - 1; ++i) {
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
size++;
}
/**
* Deletes a node at the head
*/
public void deleteHead() {
deleteNth(0);
}
/**
* Deletes an element at the tail
*/
public void delete() {
deleteNth(size - 1);
}
/**
* Deletes an element at Nth position
*/
public void deleteNth(int position) {
checkBounds(position, 0, size - 1);
if (position == 0) {
head = head.next;
/* clear to let GC do its work */
size--;
return;
}
SinglyLinkedListNode cur = head;
for (int i = 0; i < position - 1; ++i) {
cur = cur.next;
}
cur.next = cur.next.next;
size--;
}
/**
* Return element at special index.
*
* @param index given index of element
* @return element at special index.
*/
public int getNth(int index) {
checkBounds(index, 0, size - 1);
SinglyLinkedListNode cur = head;
for (int i = 0; i < index; ++i) {
cur = cur.next;
}
return cur.value;
}
/**
* @param position to check position
* @param low low index
* @param high high index
* @throws IndexOutOfBoundsException if {@code position} not in range
* {@code low} to {@code high}
*/
public void checkBounds(int position, int low, int high) {
if (position > high || position < low) {
throw new IndexOutOfBoundsException(position + "");
}
}
/**
* Driver Code
*/
public static void main(String[] arg) {
SinglyLinkedList list = new SinglyLinkedList();
assert list.isEmpty();
assert list.size() == 0 && list.count() == 0;
assert list.toString().isEmpty();
/* Test insert function */
list.insertHead(5);
list.insertHead(7);
list.insertHead(10);
list.insert(3);
list.insertNth(1, 4);
assert list.toString().equals("10->7->5->3->1");
System.out.println(list);
/* Test search function */
assert list.search(10) && list.search(5) && list.search(1) && !list.search(100);
/* Test get function */
assert list.getNth(0) == 10 && list.getNth(2) == 5 && list.getNth(4) == 1;
/* Test delete function */
list.deleteHead();
list.deleteNth(1);
list.delete();
assert list.toString().equals("7->3");
System.out.println(list);
assert list.size == 2 && list.size() == list.count();
list.clear();
assert list.isEmpty();
try {
list.delete();
assert false;
/* this should not happen */
} catch (Exception e) {
assert true;
/* this should happen */
}
SinglyLinkedList instance = new SinglyLinkedList();
SinglyLinkedListNode head = new SinglyLinkedListNode(0, new SinglyLinkedListNode(2, new SinglyLinkedListNode(3, new SinglyLinkedListNode(3, new SinglyLinkedListNode(4)))));
instance.setHead(head);
instance.deleteDuplicates();
instance.print();
}
@Override
public Iterator<Integer> iterator() {
return new SinglyLinkedListIterator();
}
private class SinglyLinkedListIterator implements Iterator<Integer> {
private SinglyLinkedListNode current;
SinglyLinkedListIterator() {
current = head;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
final var value = current.value;
current = current.next;
return value;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/DoublyLinkedList.java | package com.thealgorithms.datastructures.lists;
/**
* This class implements a DoublyLinkedList. This is done using the classes
* LinkedList and Link.
*
* <p>
* A linked list is similar to an array, it holds values. However, links in a
* linked list do not have indexes. With a linked list you do not need to
* predetermine it's size as it grows and shrinks as it is edited. This is an
* example of a double ended, doubly linked list. Each link references the next
* link and the previous one.
*
* @author Unknown
*/
public final class DoublyLinkedList {
/**
* Head refers to the front of the list
*/
protected Link head;
/**
* Tail refers to the back of the list
*/
private Link tail;
/**
* Link Operations to perform operations on nodes of the list
*/
private LinkOperations linkOperations;
/**
* Default Constructor
*/
public DoublyLinkedList() {
head = null;
tail = null;
}
/**
* Constructs a list containing the elements of the array
*
* @param array the array whose elements are to be placed into this list
* @throws NullPointerException if the specified collection is null
*/
public DoublyLinkedList(int[] array) {
if (array == null) {
throw new NullPointerException();
}
for (int i : array) {
linkOperations.insertTail(i, this);
}
}
/**
* Returns true if list is empty
*
* @return true if list is empty
*/
public boolean isEmpty() {
return (head == null);
}
/**
* Prints contents of the list
*/
public void display() { // Prints contents of the list
Link current = head;
while (current != null) {
current.displayLink();
current = current.next;
}
System.out.println();
}
/**
* Prints the contents of the list in reverse order
*/
public void displayBackwards() {
Link current = tail;
while (current != null) {
current.displayLink();
current = current.previous;
}
System.out.println();
}
}
/**
* This class is used to implement the nodes of the linked list.
*
* @author Unknown
*/
class Link {
/**
* Value of node
*/
public int value;
/**
* This points to the link in front of the new link
*/
public Link next;
/**
* This points to the link behind the new link
*/
public Link previous;
/**
* Constructor
*
* @param value Value of node
*/
Link(int value) {
this.value = value;
}
/**
* Displays the node
*/
public void displayLink() {
System.out.print(value + " ");
}
/**
* Main Method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
DoublyLinkedList myList = new DoublyLinkedList();
LinkOperations linkOperations = new LinkOperations();
linkOperations.insertHead(13, myList);
linkOperations.insertHead(7, myList);
linkOperations.insertHead(10, myList);
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.displayBackwards();
linkOperations.insertTail(11, myList);
myList.display(); // <-- 10(head) <--> 7 <--> 13 <--> 11(tail) -->
myList.displayBackwards();
linkOperations.deleteTail();
myList.display(); // <-- 10(head) <--> 7 <--> 13(tail) -->
myList.displayBackwards();
linkOperations.delete(7);
myList.display(); // <-- 10(head) <--> 13(tail) -->
myList.displayBackwards();
linkOperations.insertOrdered(23, myList);
linkOperations.insertOrdered(67, myList);
linkOperations.insertOrdered(3, myList);
myList.display(); // <-- 3(head) <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
linkOperations.insertElementByIndex(5, 1, myList);
myList.display(); // <-- 3(head) <--> 5 <--> 10 <--> 13 <--> 23 <--> 67(tail) -->
myList.displayBackwards();
linkOperations.reverse(); // <-- 67(head) <--> 23 <--> 13 <--> 10 <--> 5 <--> 3(tail) -->
myList.display();
linkOperations.clearList();
myList.display();
myList.displayBackwards();
linkOperations.insertHead(20, myList);
myList.display();
myList.displayBackwards();
}
}
/*
* This class implements the operations of the Link nodes.
*/
class LinkOperations {
/**
* Head refers to the front of the list
*/
private Link head;
/**
* Tail refers to the back of the list
*/
private Link tail;
/**
* Size refers to the number of elements present in the list
*/
private int size;
/**
* Insert an element at the head
*
* @param x Element to be inserted
*/
public void insertHead(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x); // Create a new link with a value attached to it
if (doublyLinkedList.isEmpty()) { // Set the first element added to be the tail
tail = newLink;
} else {
head.previous = newLink; // newLink <-- currenthead(head)
}
newLink.next = head; // newLink <--> currenthead(head)
head = newLink; // newLink(head) <--> oldhead
++size;
}
/**
* Insert an element at the tail
*
* @param x Element to be inserted
*/
public void insertTail(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x);
newLink.next = null; // currentTail(tail) newlink -->
if (doublyLinkedList.isEmpty()) { // Check if there are no elements in list then it adds first element
tail = newLink;
head = tail;
} else {
tail.next = newLink; // currentTail(tail) --> newLink -->
newLink.previous = tail; // currentTail(tail) <--> newLink -->
tail = newLink; // oldTail <--> newLink(tail) -->
}
++size;
}
/**
* Insert an element at the index
*
* @param x Element to be inserted
* @param index Index(from start) at which the element x to be inserted
*/
public void insertElementByIndex(int x, int index, DoublyLinkedList doublyLinkedList) {
if (index > size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
if (index == 0) {
insertHead(x, doublyLinkedList);
} else {
if (index == size) {
insertTail(x, doublyLinkedList);
} else {
Link newLink = new Link(x);
Link previousLink = head; //
for (int i = 1; i < index; i++) { // Loop to reach the index
previousLink = previousLink.next;
}
// previousLink is the Link at index - 1 from start
previousLink.next.previous = newLink;
newLink.next = previousLink.next;
newLink.previous = previousLink;
previousLink.next = newLink;
}
}
++size;
}
/**
* Delete the element at the head
*
* @return The new head
*/
public Link deleteHead() {
Link temp = head;
head = head.next; // oldHead <--> 2ndElement(head)
if (head == null) {
tail = null;
} else {
head.previous = null; // oldHead --> 2ndElement(head) nothing pointing at old head so
// will be removed
}
--size;
return temp;
}
/**
* Delete the element at the tail
*
* @return The new tail
*/
public Link deleteTail() {
Link temp = tail;
tail = tail.previous; // 2ndLast(tail) <--> oldTail --> null
if (tail == null) {
head = null;
} else {
tail.next = null; // 2ndLast(tail) --> null
}
--size;
return temp;
}
/**
* Delete the element from somewhere in the list
*
* @param x element to be deleted
* @return Link deleted
*/
public void delete(int x) {
Link current = head;
while (current.value != x) { // Find the position to delete
if (current != tail) {
current = current.next;
} else { // If we reach the tail and the element is still not found
throw new RuntimeException("The element to be deleted does not exist!");
}
}
if (current == head) {
deleteHead();
} else if (current == tail) {
deleteTail();
} else { // Before: 1 <--> 2(current) <--> 3
current.previous.next = current.next; // 1 --> 3
current.next.previous = current.previous; // 1 <--> 3
}
--size;
}
/**
* Inserts element and reorders
*
* @param x Element to be added
*/
public void insertOrdered(int x, DoublyLinkedList doublyLinkedList) {
Link newLink = new Link(x);
Link current = head;
while (current != null && x > current.value) { // Find the position to insert
current = current.next;
}
if (current == head) {
insertHead(x, doublyLinkedList);
} else if (current == null) {
insertTail(x, doublyLinkedList);
} else { // Before: 1 <--> 2(current) <--> 3
newLink.previous = current.previous; // 1 <-- newLink
current.previous.next = newLink; // 1 <--> newLink
newLink.next = current; // 1 <--> newLink --> 2(current) <--> 3
current.previous = newLink; // 1 <--> newLink <--> 2(current) <--> 3
}
++size;
}
/**
* Deletes the passed node from the current list
*
* @param z Element to be deleted
*/
public void deleteNode(Link z) {
if (z.next == null) {
deleteTail();
} else if (z == head) {
deleteHead();
} else { // before <-- 1 <--> 2(z) <--> 3 -->
z.previous.next = z.next; // 1 --> 3
z.next.previous = z.previous; // 1 <--> 3
}
--size;
}
public void removeDuplicates(DoublyLinkedList l) {
Link linkOne = l.head;
while (linkOne.next != null) { // list is present
Link linkTwo = linkOne.next; // second link for comparison
while (linkTwo.next != null) {
if (linkOne.value == linkTwo.value) { // if there are duplicates values then
delete(linkTwo.value); // delete the link
}
linkTwo = linkTwo.next; // go to next link
}
linkOne = linkOne.next; // go to link link to iterate the whole list again
}
}
/**
* Reverses the list in place
*/
public void reverse() {
// Keep references to the head and tail
Link thisHead = this.head;
Link thisTail = this.tail;
// Flip the head and tail references
this.head = thisTail;
this.tail = thisHead;
// While the link we're visiting is not null, flip the
// next and previous links
Link nextLink = thisHead;
while (nextLink != null) {
Link nextLinkNext = nextLink.next;
Link nextLinkPrevious = nextLink.previous;
nextLink.next = nextLinkPrevious;
nextLink.previous = nextLinkNext;
// Now, we want to go to the next link
nextLink = nextLinkNext;
}
}
/**
* Clears List
*/
public void clearList() {
head = null;
tail = null;
size = 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java | src/main/java/com/thealgorithms/datastructures/lists/CountSinglyLinkedListRecursion.java | package com.thealgorithms.datastructures.lists;
/**
* CountSinglyLinkedListRecursion extends a singly linked list to include a
* recursive count method, which calculates the number of nodes in the list.
*/
public class CountSinglyLinkedListRecursion extends SinglyLinkedList {
/**
* Recursively calculates the number of nodes in the list.
*
* @param head the head node of the list segment being counted.
* @return the count of nodes from the given head node onward.
*/
private int countRecursion(SinglyLinkedListNode head) {
return head == null ? 0 : 1 + countRecursion(head.next);
}
/**
* Returns the total number of nodes in the list by invoking the recursive
* count helper method.
*
* @return the total node count in the list.
*/
@Override
public int count() {
return countRecursion(getHead());
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/CircleLinkedList.java | package com.thealgorithms.datastructures.lists;
/**
* This class is a circular singly linked list implementation. In a circular linked list,
* the last node points back to the first node, creating a circular chain.
*
* <p>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 <E> the type of elements held in this list
*/
@SuppressWarnings("rawtypes")
public class CircleLinkedList<E> {
/**
* A static nested class representing a node in the circular linked list.
*
* @param <E> the type of element stored in the node
*/
static final class Node<E> {
Node<E> next;
E value;
private Node(E value, Node<E> next) {
this.value = value;
this.next = next;
}
}
private int size;
Node<E> head = null;
private Node<E> tail;
/**
* Initializes a new circular linked list. A dummy head node is used for simplicity,
* pointing initially to itself to ensure the list is never empty.
*/
public CircleLinkedList() {
head = new Node<>(null, head);
tail = head;
size = 0;
}
/**
* Returns the current size of the list.
*
* @return the number of elements in the list
*/
public int getSize() {
return size;
}
/**
* Appends a new element to the end of the list. Throws a NullPointerException if
* a null value is provided.
*
* @param value the value to append to the list
* @throws NullPointerException if the value is null
*/
public void append(E value) {
if (value == null) {
throw new NullPointerException("Cannot add null element to the list");
}
if (tail == null) {
tail = new Node<>(value, head);
head.next = tail;
} else {
tail.next = new Node<>(value, head);
tail = tail.next;
}
size++;
}
/**
* Returns a string representation of the list in the format "[ element1, element2, ... ]".
* An empty list is represented as "[]".
*
* @return the string representation of the list
*/
public String toString() {
if (size == 0) {
return "[]";
}
StringBuilder sb = new StringBuilder("[ ");
Node<E> current = head.next;
while (current != head) {
sb.append(current.value);
if (current.next != head) {
sb.append(", ");
}
current = current.next;
}
sb.append(" ]");
return sb.toString();
}
/**
* Removes and returns the element at the specified position in the list.
* Throws an IndexOutOfBoundsException if the position is invalid.
*
* @param pos the position of the element to remove
* @return the value of the removed element
* @throws IndexOutOfBoundsException if the position is out of range
*/
public E remove(int pos) {
if (pos >= size || pos < 0) {
throw new IndexOutOfBoundsException("Position out of bounds");
}
Node<E> before = head;
for (int i = 1; i <= pos; i++) {
before = before.next;
}
Node<E> destroy = before.next;
E saved = destroy.value;
before.next = destroy.next;
if (destroy == tail) {
tail = before;
}
destroy = null;
size--;
return saved;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java | src/main/java/com/thealgorithms/datastructures/lists/RotateSinglyLinkedLists.java | package com.thealgorithms.datastructures.lists;
/**
* The RotateSinglyLinkedLists class provides a method to rotate a singly linked list
* to the right by a specified number of positions.
* <p>
* In a right rotation by `k` steps, each node in the list moves `k` positions to the right.
* Nodes that are rotated off the end of the list are placed back at the beginning.
* </p>
* <p>
* Example:
* Given linked list: 1 -> 2 -> 3 -> 4 -> 5 and k = 2, the output will be:
* 4 -> 5 -> 1 -> 2 -> 3.
* </p>
* <p>
* Edge Cases:
* <ul>
* <li>If the list is empty, returns null.</li>
* <li>If `k` is 0 or a multiple of the list length, the list remains unchanged.</li>
* </ul>
* </p>
* <p>
* Complexity:
* <ul>
* <li>Time Complexity: O(n), where n is the number of nodes in the linked list.</li>
* <li>Space Complexity: O(1), as we only use a constant amount of additional space.</li>
* </ul>
* </p>
*
* Author: Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
*/
public class RotateSinglyLinkedLists {
/**
* Rotates a singly linked list to the right by `k` positions.
*
* @param head The head node of the singly linked list.
* @param k The number of positions to rotate the list to the right.
* @return The head of the rotated linked list.
*/
public SinglyLinkedListNode rotateRight(SinglyLinkedListNode head, int k) {
if (head == null || head.next == null || k == 0) {
return head;
}
SinglyLinkedListNode curr = head;
int len = 1;
while (curr.next != null) {
curr = curr.next;
len++;
}
curr.next = head;
k = k % len;
k = len - k;
while (k > 0) {
curr = curr.next;
k--;
}
head = curr.next;
curr.next = null;
return head;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/SkipList.java | src/main/java/com/thealgorithms/datastructures/lists/SkipList.java | package com.thealgorithms.datastructures.lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Skip list is a data structure that allows {@code O(log n)} search complexity
* as well as {@code O(log n)} insertion complexity within an ordered sequence
* of {@code n} elements. Thus it can get the best features of a sorted array
* (for searching) while maintaining a linked list-like structure that allows
* insertion, which is not possible with a static array.
* <p>
* A skip list is built in layers. The bottom layer is an ordinary ordered
* linked list. Each higher layer acts as an "express lane" for the lists
* below.
* <pre>
* [ ] ------> [ ] --> [ ]
* [ ] --> [ ] [ ] --> [ ]
* [ ] [ ] [ ] [ ] [ ] [ ]
* H 0 1 2 3 4
* </pre>
*
* @param <E> type of elements
* @see <a href="https://en.wikipedia.org/wiki/Skip_list">Wiki. Skip list</a>
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class SkipList<E extends Comparable<E>> {
/**
* Node before first node.
*/
private final Node<E> head;
/**
* Maximum layers count.
* Calculated by {@link #heightStrategy}.
*/
private final int height;
/**
* Function for determining height of new nodes.
* @see HeightStrategy
*/
private final HeightStrategy heightStrategy;
/**
* Current count of elements in list.
*/
private int size;
private static final int DEFAULT_CAPACITY = 100;
public SkipList() {
this(DEFAULT_CAPACITY, new BernoulliHeightStrategy());
}
public SkipList(int expectedCapacity, HeightStrategy heightStrategy) {
this.heightStrategy = heightStrategy;
this.height = heightStrategy.height(expectedCapacity);
this.head = new Node<>(null, this.height);
this.size = 0;
}
public void add(E e) {
Objects.requireNonNull(e);
Node<E> current = head;
int layer = height;
Node<E>[] toFix = new Node[height + 1];
while (layer >= 0) {
Node<E> next = current.next(layer);
if (next == null || next.getValue().compareTo(e) > 0) {
toFix[layer] = current;
layer--;
} else {
current = next;
}
}
int nodeHeight = heightStrategy.nodeHeight(height);
Node<E> node = new Node<>(e, nodeHeight);
for (int i = 0; i <= nodeHeight; i++) {
if (toFix[i].next(i) != null) {
node.setNext(i, toFix[i].next(i));
toFix[i].next(i).setPrevious(i, node);
}
toFix[i].setNext(i, node);
node.setPrevious(i, toFix[i]);
}
size++;
}
public E get(int index) {
int counter = -1; // head index
Node<E> current = head;
while (counter != index) {
current = current.next(0);
counter++;
}
return current.value;
}
public void remove(E e) {
Objects.requireNonNull(e);
Node<E> current = head;
int layer = height;
while (layer >= 0) {
Node<E> next = current.next(layer);
if (e.equals(current.getValue())) {
break;
} else if (next == null || next.getValue().compareTo(e) > 0) {
layer--;
} else {
current = next;
}
}
for (int i = 0; i <= layer; i++) {
current.previous(i).setNext(i, current.next(i));
if (current.next(i) != null) {
current.next(i).setPrevious(i, current.previous(i));
}
}
size--;
}
/**
* A search for a target element begins at the head element in the top
* list, and proceeds horizontally until the current element is greater
* than or equal to the target. If the current element is equal to the
* target, it has been found. If the current element is greater than the
* target, or the search reaches the end of the linked list, the procedure
* is repeated after returning to the previous element and dropping down
* vertically to the next lower list.
*
* @param e element whose presence in this list is to be tested
* @return true if this list contains the specified element
*/
public boolean contains(E e) {
Objects.requireNonNull(e);
Node<E> current = head;
int layer = height;
while (layer >= 0) {
Node<E> next = current.next(layer);
if (e.equals(current.getValue())) {
return true;
} else if (next == null || next.getValue().compareTo(e) > 0) {
layer--;
} else {
current = next;
}
}
return false;
}
public int size() {
return size;
}
/**
* Print height distribution of the nodes in a manner:
* <pre>
* [ ] --- --- [ ] --- [ ]
* [ ] --- [ ] [ ] --- [ ]
* [ ] [ ] [ ] [ ] [ ] [ ]
* H 0 1 2 3 4
* </pre>
* Values of nodes is not presented.
*
* @return string representation
*/
@Override
public String toString() {
List<boolean[]> layers = new ArrayList<>();
int sizeWithHeader = size + 1;
for (int i = 0; i <= height; i++) {
layers.add(new boolean[sizeWithHeader]);
}
Node<E> current = head;
int position = 0;
while (current != null) {
for (int i = 0; i <= current.height; i++) {
layers.get(i)[position] = true;
}
current = current.next(0);
position++;
}
Collections.reverse(layers);
String result = layers.stream()
.map(layer -> {
StringBuilder acc = new StringBuilder();
for (boolean b : layer) {
if (b) {
acc.append("[ ]");
} else {
acc.append("---");
}
acc.append(" ");
}
return acc.toString();
})
.collect(Collectors.joining("\n"));
String positions = IntStream.range(0, sizeWithHeader - 1).mapToObj(i -> String.format("%3d", i)).collect(Collectors.joining(" "));
return result + String.format("%n H %s%n", positions);
}
/**
* Value container.
* Each node have pointers to the closest nodes left and right from current
* on each layer of nodes height.
* @param <E> type of elements
*/
private static class Node<E> {
private final E value;
private final int height;
private final List<Node<E>> forward;
private final List<Node<E>> backward;
@SuppressWarnings("unchecked")
Node(E value, int height) {
this.value = value;
this.height = height;
// predefined size lists with null values in every cell
this.forward = Arrays.asList(new Node[height + 1]);
this.backward = Arrays.asList(new Node[height + 1]);
}
public Node<E> next(int layer) {
checkLayer(layer);
return forward.get(layer);
}
public void setNext(int layer, Node<E> node) {
forward.set(layer, node);
}
public void setPrevious(int layer, Node<E> node) {
backward.set(layer, node);
}
public Node<E> previous(int layer) {
checkLayer(layer);
return backward.get(layer);
}
public E getValue() {
return value;
}
private void checkLayer(int layer) {
if (layer < 0 || layer > height) {
throw new IllegalArgumentException();
}
}
}
/**
* Height strategy is a way of calculating maximum height for skip list
* and height for each node.
* @see BernoulliHeightStrategy
*/
public interface HeightStrategy {
int height(int expectedSize);
int nodeHeight(int heightCap);
}
/**
* In most common skip list realisation element in layer {@code i} appears
* in layer {@code i+1} with some fixed probability {@code p}.
* Two commonly used values for {@code p} are 1/2 and 1/4.
* Probability of appearing element in layer {@code i} could be calculated
* with <code>P = p<sup>i</sup>(1 - p)</code>
* <p>
* Maximum height that would give the best search complexity
* calculated by <code>log<sub>1/p</sub>n</code>
* where {@code n} is an expected count of elements in list.
*/
public static class BernoulliHeightStrategy implements HeightStrategy {
private final double probability;
private static final double DEFAULT_PROBABILITY = 0.5;
private static final Random RANDOM = new Random();
public BernoulliHeightStrategy() {
this.probability = DEFAULT_PROBABILITY;
}
public BernoulliHeightStrategy(double probability) {
if (probability <= 0 || probability >= 1) {
throw new IllegalArgumentException("Probability should be from 0 to 1. But was: " + probability);
}
this.probability = probability;
}
@Override
public int height(int expectedSize) {
long height = Math.round(Math.log10(expectedSize) / Math.log10(1 / probability));
if (height > Integer.MAX_VALUE) {
throw new IllegalArgumentException();
}
return (int) height;
}
@Override
public int nodeHeight(int heightCap) {
int level = 0;
double border = 100 * (1 - probability);
while (((RANDOM.nextInt(Integer.MAX_VALUE) % 100) + 1) > border) {
if (level + 1 >= heightCap) {
return level;
}
level++;
}
return level;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/SortedLinkedList.java | package com.thealgorithms.datastructures.lists;
import java.util.ArrayList;
import java.util.List;
/**
* The SortedLinkedList class represents a singly linked list that maintains its elements in sorted order.
* Elements are ordered based on their natural ordering, with smaller elements at the head and larger elements toward the tail.
* The class provides methods for inserting, deleting, and searching elements, as well as checking if the list is empty.
* <p>
* This implementation utilizes a singly linked list to maintain a dynamically sorted list.
* </p>
* <p>
* Further information can be found here:
* https://runestone.academy/ns/books/published/cppds/LinearLinked/ImplementinganOrderedList.html
* </p>
*
* <b>Usage Example:</b>
* <pre>
* SortedLinkedList list = new SortedLinkedList();
* list.insert(10);
* list.insert(5);
* list.insert(20);
* System.out.println(list); // Outputs: [5, 10, 20]
* </pre>
*/
public class SortedLinkedList {
private Node head;
private Node tail;
/**
* Initializes an empty sorted linked list.
*/
public SortedLinkedList() {
this.head = null;
this.tail = null;
}
/**
* Inserts a new integer into the list, maintaining sorted order.
*
* @param value the integer to insert
*/
public void insert(int value) {
Node newNode = new Node(value);
if (head == null) {
this.head = newNode;
this.tail = newNode;
} else if (value < head.value) {
newNode.next = this.head;
this.head = newNode;
} else if (value > tail.value) {
this.tail.next = newNode;
this.tail = newNode;
} else {
Node temp = head;
while (temp.next != null && temp.next.value < value) {
temp = temp.next;
}
newNode.next = temp.next;
temp.next = newNode;
if (newNode.next == null) {
this.tail = newNode;
}
}
}
/**
* Deletes the first occurrence of a specified integer in the list.
*
* @param value the integer to delete
* @return {@code true} if the element was found and deleted; {@code false} otherwise
*/
public boolean delete(int value) {
if (this.head == null) {
return false;
} else if (this.head.value == value) {
if (this.head.next == null) {
this.head = null;
this.tail = null;
} else {
this.head = this.head.next;
}
return true;
} else {
Node temp = this.head;
while (temp.next != null) {
if (temp.next.value == value) {
if (temp.next == this.tail) {
this.tail = temp;
}
temp.next = temp.next.next;
return true;
}
temp = temp.next;
}
return false;
}
}
/**
* Searches for a specified integer in the list.
*
* @param value the integer to search for
* @return {@code true} if the value is present in the list; {@code false} otherwise
*/
public boolean search(int value) {
Node temp = this.head;
while (temp != null) {
if (temp.value == value) {
return true;
}
temp = temp.next;
}
return false;
}
/**
* Checks if the list is empty.
*
* @return {@code true} if the list is empty; {@code false} otherwise
*/
public boolean isEmpty() {
return head == null;
}
/**
* Returns a string representation of the sorted linked list in the format [element1, element2, ...].
*
* @return a string representation of the sorted linked list
*/
@Override
public String toString() {
if (this.head != null) {
List<String> elements = new ArrayList<>();
Node temp = this.head;
while (temp != null) {
elements.add(String.valueOf(temp.value));
temp = temp.next;
}
return "[" + String.join(", ", elements) + "]";
} else {
return "[]";
}
}
/**
* Node represents an element in the sorted linked list.
*/
public final class Node {
public final int value;
public Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java | src/main/java/com/thealgorithms/datastructures/lists/FlattenMultilevelLinkedList.java | package com.thealgorithms.datastructures.lists;
/**
* Implements an algorithm to flatten a multilevel linked list.
*
* 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
* flattened list to its right.
* @see <a href="https://www.geeksforgeeks.org/flattening-a-linked-list/">GeeksforGeeks: Flattening a Linked List</a>
*/
public final class FlattenMultilevelLinkedList {
/**
* Private constructor to prevent instantiation of this utility class.
*/
private FlattenMultilevelLinkedList() {
}
/**
* Node represents an element in the multilevel linked list. It contains the
* integer data, a reference to the next node at the same level, and a
* reference to the head of a child list.
*/
static class Node {
int data;
Node next;
Node child;
Node(int data) {
this.data = data;
this.next = null;
this.child = null;
}
}
/**
* Merges two sorted linked lists (connected via the `child` pointer).
* This is a helper function for the main flatten algorithm.
*
* @param a The head of the first sorted list.
* @param b The head of the second sorted list.
* @return The head of the merged sorted list.
*/
private static Node merge(Node a, Node b) {
// If one of the lists is empty, return the other.
if (a == null) {
return b;
}
if (b == null) {
return a;
}
Node result;
// Choose the smaller value as the new head.
if (a.data < b.data) {
result = a;
result.child = merge(a.child, b);
} else {
result = b;
result.child = merge(a, b.child);
}
result.next = null; // Ensure the merged list has no `next` pointers.
return result;
}
/**
* Flattens a multilevel linked list into a single sorted list.
* The flattened list is connected using the `child` pointers.
*
* @param head The head of the top-level list (connected via `next` pointers).
* @return The head of the fully flattened and sorted list.
*/
public static Node flatten(Node head) {
// Base case: if the list is empty or has only one node, it's already flattened.
if (head == null || head.next == null) {
return head;
}
// Recursively flatten the list starting from the next node.
head.next = flatten(head.next);
// Now, merge the current list (head's child list) with the flattened rest of the list.
head = merge(head, head.next);
// Return the head of the fully merged list.
return head;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java | src/main/java/com/thealgorithms/datastructures/lists/CreateAndDetectLoop.java | package com.thealgorithms.datastructures.lists;
/**
* CreateAndDetectLoop provides utility methods for creating and detecting loops
* (cycles) in a singly linked list. Loops in a linked list are created by
* connecting the "next" pointer of one node to a previous node in the list,
* forming a cycle.
*/
public final class CreateAndDetectLoop {
/**
* Private constructor to prevent instantiation of this utility class.
*/
private CreateAndDetectLoop() {
throw new UnsupportedOperationException("Utility class");
}
/**
* Node represents an individual element in the linked list, containing
* data and a reference to the next node.
*/
static final class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
/**
* Creates a loop in a linked list by connecting the next pointer of a node
* at a specified starting position (position2) to another node at a specified
* destination position (position1). If either position is invalid, no loop
* will be created.
*
* @param head the head node of the linked list
* @param position1 the position in the list where the loop should end
* @param position2 the position in the list where the loop should start
*/
static void createLoop(Node head, int position1, int position2) {
if (position1 == 0 || position2 == 0) {
return;
}
Node node1 = head;
Node node2 = head;
int count1 = 1;
int count2 = 1;
// Traverse to the node at position1
while (count1 < position1 && node1 != null) {
node1 = node1.next;
count1++;
}
// Traverse to the node at position2
while (count2 < position2 && node2 != null) {
node2 = node2.next;
count2++;
}
// If both nodes are valid, create the loop
if (node1 != null && node2 != null) {
node2.next = node1;
}
}
/**
* Detects the presence of a loop in the linked list using Floyd's cycle-finding
* algorithm, also known as the "tortoise and hare" method.
*
* @param head the head node of the linked list
* @return true if a loop is detected, false otherwise
* @see <a href="https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare">
* Floyd's Cycle Detection Algorithm</a>
*/
static boolean detectLoop(Node head) {
Node sptr = head;
Node fptr = head;
while (fptr != null && fptr.next != null) {
sptr = sptr.next;
fptr = fptr.next.next;
if (sptr == fptr) {
return true;
}
}
return false;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedListNode.java | src/main/java/com/thealgorithms/datastructures/lists/SinglyLinkedListNode.java | package com.thealgorithms.datastructures.lists;
/**
* This class is the nodes of the SinglyLinked List. They consist of a value and
* a pointer to the node after them.
*/
class SinglyLinkedListNode {
int value;
SinglyLinkedListNode next = null;
SinglyLinkedListNode() {
}
/**
* Constructor
*
* @param value Value to be put in the node
*/
SinglyLinkedListNode(int value) {
this(value, null);
}
/**
* Constructor
*
* @param value Value to be put in the node
* @param next Reference to the next node
*/
SinglyLinkedListNode(int value, SinglyLinkedListNode next) {
this.value = value;
this.next = next;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java | src/main/java/com/thealgorithms/datastructures/heaps/LeftistHeap.java | package com.thealgorithms.datastructures.heaps;
import java.util.ArrayList;
/**
* This class implements a Leftist Heap, which is a type of priority queue
* that follows similar operations to a binary min-heap but allows for
* unbalanced structures based on the leftist property.
*
* <p>
* A Leftist Heap maintains the leftist property, which ensures that the
* left subtree is heavier than the right subtree based on the
* null-path length (npl) values. This allows for efficient merging
* of heaps and supports operations like insertion, extraction of
* the minimum element, and in-order traversal.
* </p>
*
* <p>
* For more information on Leftist Heaps, visit:
* <a href="https://iq.opengenus.org/leftist-heap/">OpenGenus</a>
* </p>
*/
public class LeftistHeap {
// Node class representing each element in the Leftist Heap
private static final class Node {
private final int element;
private int npl;
private Node left;
private Node right;
// Node constructor that initializes the element and sets child pointers to null
private Node(int element) {
this.element = element;
left = null;
right = null;
npl = 0;
}
}
private Node root;
// Constructor initializing an empty Leftist Heap
public LeftistHeap() {
root = null;
}
/**
* Checks if the heap is empty.
*
* @return true if the heap is empty; false otherwise
*/
public boolean isEmpty() {
return root == null;
}
/**
* Resets the heap to its initial state, effectively clearing all elements.
*/
public void clear() {
root = null; // Set root to null to clear the heap
}
/**
* Merges the contents of another Leftist Heap into this one.
*
* @param h1 the LeftistHeap to be merged into this heap
*/
public void merge(LeftistHeap h1) {
// Merge the current heap with the provided heap and set the provided heap's root to null
root = merge(root, h1.root);
h1.root = null;
}
/**
* Merges two nodes, maintaining the leftist property.
*
* @param a the first node
* @param b the second node
* @return the merged node maintaining the leftist property
*/
public Node merge(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
// Ensure that the leftist property is maintained
if (a.element > b.element) {
Node temp = a;
a = b;
b = temp;
}
// Merge the right child of node a with node b
a.right = merge(a.right, b);
// If left child is null, make right child the left child
if (a.left == null) {
a.left = a.right;
a.right = null;
} else {
if (a.left.npl < a.right.npl) {
Node temp = a.left;
a.left = a.right;
a.right = temp;
}
a.npl = a.right.npl + 1;
}
return a;
}
/**
* Inserts a new element into the Leftist Heap.
*
* @param a the element to be inserted
*/
public void insert(int a) {
root = merge(new Node(a), root);
}
/**
* Extracts and removes the minimum element from the heap.
*
* @return the minimum element in the heap, or -1 if the heap is empty
*/
public int extractMin() {
if (isEmpty()) {
return -1;
}
int min = root.element;
root = merge(root.left, root.right);
return min;
}
/**
* Returns a list of the elements in the heap in in-order traversal.
*
* @return an ArrayList containing the elements in in-order
*/
public ArrayList<Integer> inOrder() {
ArrayList<Integer> lst = new ArrayList<>();
inOrderAux(root, lst);
return new ArrayList<>(lst);
}
/**
* Auxiliary function for in-order traversal
*
* @param n the current node
* @param lst the list to store the elements in in-order
*/
private void inOrderAux(Node n, ArrayList<Integer> lst) {
if (n == null) {
return;
}
inOrderAux(n.left, lst);
lst.add(n.element);
inOrderAux(n.right, lst);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java | src/main/java/com/thealgorithms/datastructures/heaps/MergeKSortedArrays.java | package com.thealgorithms.datastructures.heaps;
import java.util.Comparator;
import java.util.PriorityQueue;
/**
* This class provides a method to merge multiple sorted arrays into a single sorted array.
* It utilizes a min-heap to efficiently retrieve the smallest elements from each array.
*
* 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
*/
public final class MergeKSortedArrays {
private MergeKSortedArrays() {
}
/**
* Merges k sorted arrays into one sorted array using a min-heap.
* Steps:
* 1. Create a min-heap to store elements in the format: {value, array index, element index}
* 2. Add the first element from each array to the heap
* 3. While the heap is not empty, remove the smallest element from the heap
* and add it to the result array. If there are more elements in the same array,
* add the next element to the heap.
* Continue until all elements have been processed.
* The result array will contain all elements in sorted order.
* 4. Return the result array.
*
* @param arrays a 2D array, where each subarray is sorted in non-decreasing order
* @return a single sorted array containing all elements from the input arrays
*/
public static int[] mergeKArrays(int[][] arrays) {
PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
int totalLength = 0;
for (int i = 0; i < arrays.length; i++) {
if (arrays[i].length > 0) {
minHeap.offer(new int[] {arrays[i][0], i, 0});
totalLength += arrays[i].length;
}
}
int[] result = new int[totalLength];
int index = 0;
while (!minHeap.isEmpty()) {
int[] top = minHeap.poll();
result[index++] = top[0];
if (top[2] + 1 < arrays[top[1]].length) {
minHeap.offer(new int[] {arrays[top[1]][top[2] + 1], top[1], top[2] + 1});
}
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java | src/main/java/com/thealgorithms/datastructures/heaps/IndexedPriorityQueue.java | package com.thealgorithms.datastructures.heaps;
import java.util.Arrays;
import java.util.Comparator;
import java.util.IdentityHashMap;
import java.util.Objects;
import java.util.function.Consumer;
/**
* An addressable (indexed) min-priority queue with O(log n) updates.
*
* <p>Key features:
* <ul>
* <li>Each element E is tracked by a handle (its current heap index) via a map,
* enabling O(log n) {@code remove(e)} and O(log n) key updates
* ({@code changeKey/decreaseKey/increaseKey}).</li>
* <li>The queue order is determined by the provided {@link Comparator}. If the
* comparator is {@code null}, elements must implement {@link Comparable}
* (same contract as {@link java.util.PriorityQueue}).</li>
* <li>By default this implementation uses {@link IdentityHashMap} for the index
* mapping to avoid issues with duplicate-equals elements or mutable equals/hashCode.
* If you need value-based equality, switch to {@code HashMap} and read the caveats
* in the class-level Javadoc carefully.</li>
* </ul>
*
* <h2>IMPORTANT contracts</h2>
* <ul>
* <li><b>Do not mutate comparator-relevant fields of an element directly</b> while it is
* inside the queue. Always use {@code changeKey}/{@code decreaseKey}/{@code increaseKey}
* so the heap can be restored accordingly.</li>
* <li>If you replace {@link IdentityHashMap} with {@link HashMap}, you must ensure:
* (a) no two distinct elements are {@code equals()}-equal at the same time in the queue, and
* (b) {@code equals/hashCode} of elements remain stable while enqueued.</li>
* <li>{@code peek()} returns {@code null} when empty (matching {@link java.util.PriorityQueue}).</li>
* <li>Not thread-safe.</li>
* </ul>
*
* <p>Complexities:
* {@code offer, poll, remove(e), changeKey, decreaseKey, increaseKey} are O(log n);
* {@code peek, isEmpty, size, contains} are O(1).
*/
public class IndexedPriorityQueue<E> {
/** Binary heap storage (min-heap). */
private Object[] heap;
/** Number of elements in the heap. */
private int size;
/** Comparator used for ordering; if null, elements must be Comparable. */
private final Comparator<? super E> cmp;
/**
* Index map: element -> current heap index.
* <p>We use IdentityHashMap by default to:
* <ul>
* <li>allow duplicate-equals elements;</li>
* <li>avoid corruption when equals/hashCode are mutable or not ID-based.</li>
* </ul>
* If you prefer value-based semantics, replace with HashMap<E,Integer> and
* respect the warnings in the class Javadoc.
*/
private final IdentityHashMap<E, Integer> index;
private static final int DEFAULT_INITIAL_CAPACITY = 11;
public IndexedPriorityQueue() {
this(DEFAULT_INITIAL_CAPACITY, null);
}
public IndexedPriorityQueue(Comparator<? super E> cmp) {
this(DEFAULT_INITIAL_CAPACITY, cmp);
}
public IndexedPriorityQueue(int initialCapacity, Comparator<? super E> cmp) {
if (initialCapacity < 1) {
throw new IllegalArgumentException("initialCapacity < 1");
}
this.heap = new Object[initialCapacity];
this.cmp = cmp;
this.index = new IdentityHashMap<>();
}
/** Returns current number of elements. */
public int size() {
return size;
}
/** Returns {@code true} if empty. */
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the minimum element without removing it, or {@code null} if empty.
* Matches {@link java.util.PriorityQueue#peek()} behavior.
*/
@SuppressWarnings("unchecked")
public E peek() {
return size == 0 ? null : (E) heap[0];
}
/**
* Inserts the specified element (O(log n)).
* @throws NullPointerException if {@code e} is null
* @throws ClassCastException if {@code cmp == null} and {@code e} is not Comparable,
* or if incompatible with other elements
*/
public boolean offer(E e) {
Objects.requireNonNull(e, "element is null");
if (size >= heap.length) {
grow(size + 1);
}
// Insert at the end and bubble up. siftUp will maintain 'index' for all touched nodes.
siftUp(size, e);
size++;
return true;
}
/**
* Removes and returns the minimum element (O(log n)), or {@code null} if empty.
*/
@SuppressWarnings("unchecked")
public E poll() {
if (size == 0) {
return null;
}
E min = (E) heap[0];
removeAt(0); // updates map and heap structure
return min;
}
/**
* Removes one occurrence of the specified element e (O(log n)) if present.
* Uses the index map for O(1) lookup.
*/
public boolean remove(Object o) {
Integer i = index.get(o);
if (i == null) {
return false;
}
removeAt(i);
return true;
}
/** O(1): returns whether the queue currently contains the given element reference. */
public boolean contains(Object o) {
return index.containsKey(o);
}
/** Clears the heap and the index map. */
public void clear() {
Arrays.fill(heap, 0, size, null);
index.clear();
size = 0;
}
// ------------------------------------------------------------------------------------
// Key update API
// ------------------------------------------------------------------------------------
/**
* Changes comparator-relevant fields of {@code e} via the provided {@code mutator},
* then restores the heap in O(log n) by bubbling in the correct direction.
*
* <p><b>IMPORTANT:</b> The mutator must not change {@code equals/hashCode} of {@code e}
* if you migrate this implementation to value-based indexing (HashMap).
*
* @throws IllegalArgumentException if {@code e} is not in the queue
*/
public void changeKey(E e, Consumer<E> mutator) {
Integer i = index.get(e);
if (i == null) {
throw new IllegalArgumentException("Element not in queue");
}
// Mutate fields used by comparator (do NOT mutate equality/hash if using value-based map)
mutator.accept(e);
// Try bubbling up; if no movement occurred, bubble down.
if (!siftUp(i)) {
siftDown(i);
}
}
/**
* Faster variant if the new key is strictly smaller (higher priority).
* Performs a single sift-up (O(log n)).
*/
public void decreaseKey(E e, Consumer<E> mutator) {
Integer i = index.get(e);
if (i == null) {
throw new IllegalArgumentException("Element not in queue");
}
mutator.accept(e);
siftUp(i);
}
/**
* Faster variant if the new key is strictly larger (lower priority).
* Performs a single sift-down (O(log n)).
*/
public void increaseKey(E e, Consumer<E> mutator) {
Integer i = index.get(e);
if (i == null) {
throw new IllegalArgumentException("Element not in queue");
}
mutator.accept(e);
siftDown(i);
}
// ------------------------------------------------------------------------------------
// Internal utilities
// ------------------------------------------------------------------------------------
/** Grows the internal array to accommodate at least {@code minCapacity}. */
private void grow(int minCapacity) {
int old = heap.length;
int pref = (old < 64) ? old + 2 : old + (old >> 1); // +2 if small, else +50%
int newCap = Math.max(minCapacity, pref);
heap = Arrays.copyOf(heap, newCap);
}
@SuppressWarnings("unchecked")
private int compare(E a, E b) {
if (cmp != null) {
return cmp.compare(a, b);
}
return ((Comparable<? super E>) a).compareTo(b);
}
/**
* Inserts item {@code x} at position {@code k}, bubbling up while maintaining the heap.
* Also maintains the index map for all moved elements.
*/
@SuppressWarnings("unchecked")
private void siftUp(int k, E x) {
while (k > 0) {
int p = (k - 1) >>> 1;
E e = (E) heap[p];
if (compare(x, e) >= 0) {
break;
}
heap[k] = e;
index.put(e, k);
k = p;
}
heap[k] = x;
index.put(x, k);
}
/**
* Attempts to bubble up the element currently at {@code k}.
* @return true if it moved; false otherwise.
*/
@SuppressWarnings("unchecked")
private boolean siftUp(int k) {
int orig = k;
E x = (E) heap[k];
while (k > 0) {
int p = (k - 1) >>> 1;
E e = (E) heap[p];
if (compare(x, e) >= 0) {
break;
}
heap[k] = e;
index.put(e, k);
k = p;
}
if (k != orig) {
heap[k] = x;
index.put(x, k);
return true;
}
return false;
}
/** Bubbles down the element currently at {@code k}. */
@SuppressWarnings("unchecked")
private void siftDown(int k) {
int n = size;
E x = (E) heap[k];
int half = n >>> 1; // loop while k has at least one child
while (k < half) {
int child = (k << 1) + 1; // assume left is smaller
E c = (E) heap[child];
int r = child + 1;
if (r < n && compare(c, (E) heap[r]) > 0) {
child = r;
c = (E) heap[child];
}
if (compare(x, c) <= 0) {
break;
}
heap[k] = c;
index.put(c, k);
k = child;
}
heap[k] = x;
index.put(x, k);
}
/**
* Removes the element at heap index {@code i}, restoring the heap afterwards.
* <p>Returns nothing; the standard {@code PriorityQueue} returns a displaced
* element in a rare case to help its iterator. We don't need that here, so
* we keep the API simple.
*/
@SuppressWarnings("unchecked")
private void removeAt(int i) {
int n = --size; // last index after removal
E moved = (E) heap[n];
E removed = (E) heap[i];
heap[n] = null; // help GC
index.remove(removed); // drop mapping for removed element
if (i == n) {
return; // removed last element; done
}
heap[i] = moved;
index.put(moved, i);
// Try sift-up first (cheap if key decreased); if no movement, sift-down.
if (!siftUp(i)) {
siftDown(i);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/Heap.java | src/main/java/com/thealgorithms/datastructures/heaps/Heap.java | package com.thealgorithms.datastructures.heaps;
/**
* Interface common to heap data structures.<br>
*
* <p>
* Heaps are tree-like data structures that allow storing elements in a specific
* way. Each node corresponds to an element and has one parent node (except for
* the root) and at most two children nodes. Every element contains a key, and
* those keys indicate how the tree shall be built. For instance, for a
* min-heap, the key of a node shall be greater than or equal to its parent's
* and lower than or equal to its children's (the opposite rule applies to a
* max-heap).
*
* <p>
* All heap-related operations (inserting or deleting an element, extracting the
* min or max) are performed in O(log n) time.
*
* @author Nicolas Renard
*/
public interface Heap {
/**
* @return the top element in the heap, the one with lowest key for min-heap
* or with the highest key for max-heap
* @throws EmptyHeapException if heap is empty
*/
HeapElement getElement() throws EmptyHeapException;
/**
* Inserts an element in the heap. Adds it to then end and toggle it until
* it finds its right position.
*
* @param element an instance of the HeapElement class.
*/
void insertElement(HeapElement element);
/**
* Delete an element in the heap.
*
* @param elementIndex int containing the position in the heap of the
* element to be deleted.
*/
void deleteElement(int elementIndex) throws EmptyHeapException;
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java | src/main/java/com/thealgorithms/datastructures/heaps/MinHeap.java | package com.thealgorithms.datastructures.heaps;
import java.util.ArrayList;
import java.util.List;
/**
* 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<HeapElement> elements = Arrays.asList(
* new HeapElement(5, "Five"),
* new HeapElement(2, "Two")
* );
* MinHeap heap = new MinHeap(elements);
* heap.insertElement(new HeapElement(1, "One"));
* HeapElement min = heap.getElement(); // Returns and removes the minimum element
* ```
*
* @author Nicolas Renard
*/
public class MinHeap implements Heap {
private final List<HeapElement> minHeap;
/**
* Constructs a new MinHeap from a list of elements.
* Null elements in the input list are ignored with a warning message.
*
* @param listElements List of HeapElement objects to initialize the heap
* @throws IllegalArgumentException if the input list is null
*/
public MinHeap(List<HeapElement> listElements) {
if (listElements == null) {
throw new IllegalArgumentException("Input list cannot be null");
}
minHeap = new ArrayList<>();
// Safe initialization: directly add elements first
for (HeapElement heapElement : listElements) {
if (heapElement != null) {
minHeap.add(heapElement);
} else {
System.out.println("Null element. Not added to heap");
}
}
// Heapify the array bottom-up
for (int i = minHeap.size() / 2; i >= 0; i--) {
heapifyDown(i + 1);
}
if (minHeap.isEmpty()) {
System.out.println("No element has been added, empty heap.");
}
}
/**
* Retrieves the element at the specified index without removing it.
* Note: The index is 1-based for consistency with heap operations.
*
* @param elementIndex 1-based index of the element to retrieve
* @return HeapElement at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > minHeap.size())) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + minHeap.size() + "]");
}
return minHeap.get(elementIndex - 1);
}
/**
* Retrieves the key value of an element at the specified index.
*
* @param elementIndex 1-based index of the element
* @return double value representing the key
* @throws IndexOutOfBoundsException if the index is invalid
*/
private double getElementKey(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > minHeap.size())) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + minHeap.size() + "]");
}
return minHeap.get(elementIndex - 1).getKey();
}
/**
* Swaps two elements in the heap.
*
* @param index1 1-based index of first element
* @param index2 1-based index of second element
*/
private void swap(int index1, int index2) {
HeapElement temporaryElement = minHeap.get(index1 - 1);
minHeap.set(index1 - 1, minHeap.get(index2 - 1));
minHeap.set(index2 - 1, temporaryElement);
}
/**
* Maintains heap properties by moving an element down the heap.
* Used specifically during initialization.
*
* @param elementIndex 1-based index of the element to heapify
*/
private void heapifyDown(int elementIndex) {
int smallest = elementIndex - 1; // Convert to 0-based index
int leftChild = 2 * elementIndex - 1;
int rightChild = 2 * elementIndex;
// Check if left child is smaller than root
if (leftChild < minHeap.size() && minHeap.get(leftChild).getKey() < minHeap.get(smallest).getKey()) {
smallest = leftChild;
}
// Check if right child is smaller than smallest so far
if (rightChild < minHeap.size() && minHeap.get(rightChild).getKey() < minHeap.get(smallest).getKey()) {
smallest = rightChild;
}
// If smallest is not root
if (smallest != elementIndex - 1) {
HeapElement swap = minHeap.get(elementIndex - 1);
minHeap.set(elementIndex - 1, minHeap.get(smallest));
minHeap.set(smallest, swap);
// Recursively heapify the affected sub-tree
heapifyDown(smallest + 1); // Convert back to 1-based index
}
}
/**
* Moves an element up the heap until heap properties are satisfied.
* This operation is called after insertion to maintain heap properties.
*
* @param elementIndex 1-based index of the element to move up
*/
private void toggleUp(int elementIndex) {
if (elementIndex <= 1) {
return;
}
double key = minHeap.get(elementIndex - 1).getKey();
int parentIndex = (int) Math.floor(elementIndex / 2.0);
while (elementIndex > 1 && getElementKey(parentIndex) > key) {
swap(elementIndex, parentIndex);
elementIndex = parentIndex;
parentIndex = (int) Math.floor(elementIndex / 2.0);
}
}
/**
* Moves an element down the heap until heap properties are satisfied.
* This operation is called after deletion to maintain heap properties.
*
* @param elementIndex 1-based index of the element to move down
*/
private void toggleDown(int elementIndex) {
double key = minHeap.get(elementIndex - 1).getKey();
int size = minHeap.size();
while (true) {
int smallest = elementIndex;
int leftChild = 2 * elementIndex;
int rightChild = 2 * elementIndex + 1;
if (leftChild <= size && getElementKey(leftChild) < key) {
smallest = leftChild;
}
if (rightChild <= size && getElementKey(rightChild) < getElementKey(smallest)) {
smallest = rightChild;
}
if (smallest == elementIndex) {
break;
}
swap(elementIndex, smallest);
elementIndex = smallest;
}
}
/**
* Extracts and returns the minimum element from the heap.
*
* @return HeapElement with the lowest key
* @throws EmptyHeapException if the heap is empty
*/
private HeapElement extractMin() throws EmptyHeapException {
if (minHeap.isEmpty()) {
throw new EmptyHeapException("Cannot extract from empty heap");
}
HeapElement result = minHeap.getFirst();
deleteElement(1);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public void insertElement(HeapElement element) {
if (element == null) {
throw new IllegalArgumentException("Cannot insert null element");
}
minHeap.add(element);
toggleUp(minHeap.size());
}
/**
* {@inheritDoc}
*/
@Override
public void deleteElement(int elementIndex) throws EmptyHeapException {
if (minHeap.isEmpty()) {
throw new EmptyHeapException("Cannot delete from empty heap");
}
if ((elementIndex > minHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + minHeap.size() + "]");
}
// Replace with last element and remove last position
minHeap.set(elementIndex - 1, minHeap.getLast());
minHeap.removeLast();
// No need to toggle if we just removed the last element
if (!minHeap.isEmpty() && elementIndex <= minHeap.size()) {
// Determine whether to toggle up or down
if (elementIndex > 1 && getElementKey(elementIndex) < getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} else {
toggleDown(elementIndex);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public HeapElement getElement() throws EmptyHeapException {
return extractMin();
}
/**
* Returns the current size of the heap.
*
* @return number of elements in the heap
*/
public int size() {
return minHeap.size();
}
/**
* Checks if the heap is empty.
*
* @return true if the heap contains no elements
*/
public boolean isEmpty() {
return minHeap.isEmpty();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java | src/main/java/com/thealgorithms/datastructures/heaps/FibonacciHeap.java | package com.thealgorithms.datastructures.heaps;
/**
* The {@code FibonacciHeap} class implements a Fibonacci Heap data structure,
* which is a collection of trees that satisfy the minimum heap property.
* This heap allows for efficient merging of heaps, as well as faster
* decrease-key and delete operations compared to other heap data structures.
*
* <p>Key features of the Fibonacci Heap include:
* <ul>
* <li>Amortized O(1) time complexity for insert and decrease-key operations.</li>
* <li>Amortized O(log n) time complexity for delete and delete-min operations.</li>
* <li>Meld operation that combines two heaps in O(1) time.</li>
* <li>Potential function that helps analyze the amortized time complexity.</li>
* </ul>
*
* <p>This implementation maintains additional statistics such as the total number
* of link and cut operations performed during the lifetime of the heap, which can
* be accessed through static methods.
*
* <p>The Fibonacci Heap is composed of nodes represented by the inner class
* {@code HeapNode}. Each node maintains a key, rank, marked status, and pointers
* to its children and siblings. Nodes can be linked and cut as part of the heap
* restructuring processes.
*
* @see HeapNode
*/
public class FibonacciHeap {
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
private HeapNode min;
private static int totalLinks = 0;
private static int totalCuts = 0;
private int numOfTrees = 0;
private int numOfHeapNodes = 0;
private int markedHeapNodesCounter = 0;
/*
* a constructor for an empty Heap
* set the min to be null
*/
public FibonacciHeap() {
this.min = null;
}
/*
* a constructor for a Heap with one element
* set the min to be the HeapNode with the given key
* @pre key>=0
* @post empty == false
*/
public FibonacciHeap(int key) {
this.min = new HeapNode(key);
this.numOfTrees++;
this.numOfHeapNodes++;
}
/*
* check if the heap is empty
* $ret == true - if the tree is empty
*/
public boolean empty() {
return (this.min == null);
}
/**
* Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap.
*
* @pre key>=0
* @post (numOfnodes = = $prev numOfnodes + 1)
* @post empty == false
* $ret = the HeapNode we inserted
*/
public HeapNode insert(int key) {
HeapNode toInsert = new HeapNode(key); // creates the node
if (this.empty()) {
this.min = toInsert;
} else { // tree is not empty
min.setNext(toInsert);
this.updateMin(toInsert);
}
this.numOfHeapNodes++;
this.numOfTrees++;
return toInsert;
}
/**
* Delete the node containing the minimum key in the heap
* updates new min
*
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void deleteMin() {
if (this.empty()) {
return;
}
if (this.numOfHeapNodes == 1) { // if there is only one tree
this.min = null;
this.numOfTrees--;
this.numOfHeapNodes--;
return;
}
// change all children's parent to null//
if (this.min.child != null) { // min has a child
HeapNode child = this.min.child;
HeapNode tmpChild = child;
child.parent = null;
while (child.next != tmpChild) {
child = child.next;
child.parent = null;
}
}
// delete the node//
if (this.numOfTrees > 1) {
(this.min.prev).next = this.min.next;
(this.min.next).prev = this.min.prev;
if (this.min.child != null) {
(this.min.prev).setNext(this.min.child);
}
} else { // this.numOfTrees = 1
this.min = this.min.child;
}
this.numOfHeapNodes--;
this.successiveLink(this.min.getNext());
}
/**
* Return the node of the heap whose key is minimal.
* $ret == null if (empty==true)
*/
public HeapNode findMin() {
return this.min;
}
/**
* Meld the heap with heap2
*
* @pre heap2 != null
* @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes)
*/
public void meld(FibonacciHeap heap2) {
if (heap2.empty()) {
return;
}
if (this.empty()) {
this.min = heap2.min;
} else {
this.min.setNext(heap2.min);
this.updateMin(heap2.min);
}
this.numOfTrees += heap2.numOfTrees;
this.numOfHeapNodes += heap2.numOfHeapNodes;
}
/**
* Return the number of elements in the heap
* $ret == 0 if heap is empty
*/
public int size() {
return this.numOfHeapNodes;
}
/**
* Return a counters array, where the value of the i-th index is the number of trees with rank i
* in the heap. returns an empty array for an empty heap
*/
public int[] countersRep() {
if (this.empty()) {
return new int[0]; /// return an empty array
}
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
rankArray[this.min.rank]++;
HeapNode curr = this.min.next;
while (curr != this.min) {
rankArray[curr.rank]++;
curr = curr.next;
}
return rankArray;
}
/**
* Deletes the node x from the heap (using decreaseKey(x) to -1)
*
* @pre heap contains x
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void delete(HeapNode x) {
this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1)
this.deleteMin(); // delete it
}
/**
* The function decreases the key of the node x by delta.
*
* @pre x.key >= delta (we don't realize it when calling from delete())
* @pre heap contains x
*/
private void decreaseKey(HeapNode x, int delta) {
int newKey = x.getKey() - delta;
x.key = newKey;
if (x.isRoot()) { // no parent to x
this.updateMin(x);
return;
}
if (x.getKey() >= x.parent.getKey()) {
return;
} // we don't need to cut
HeapNode prevParent = x.parent;
this.cut(x);
this.cascadingCuts(prevParent);
}
/**
* returns the current potential of the heap, which is:
* Potential = #trees + 2*#markedNodes
*/
public int potential() {
return numOfTrees + (2 * markedHeapNodesCounter);
}
/**
* This static function returns the total number of link operations made during the run-time of
* the program. A link operation is the operation which gets as input two trees of the same
* rank, and generates a tree of rank bigger by one.
*/
public static int totalLinks() {
return totalLinks;
}
/**
* This static function returns the total number of cut operations made during the run-time of
* the program. A cut operation is the operation which disconnects a subtree from its parent
* (during decreaseKey/delete methods).
*/
public static int totalCuts() {
return totalCuts;
}
/*
* updates the min of the heap (if needed)
* @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key)
*/
private void updateMin(HeapNode posMin) {
if (posMin.getKey() < this.min.getKey()) {
this.min = posMin;
}
}
/*
* Recursively "runs" all the way up from @param (curr) and mark the nodes.
* stop the recursion if we had arrived to a marked node or to a root.
* if we arrived to a marked node, we cut it and continue recursively.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion
curr.mark();
if (!curr.isRoot()) {
this.markedHeapNodesCounter++;
}
} else {
if (curr.isRoot()) {
return;
}
HeapNode prevParent = curr.parent;
this.cut(curr);
this.cascadingCuts(prevParent);
}
}
/*
* cut a node (and his "subtree") from his origin tree and connect it to the heap as a new tree.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cut(HeapNode curr) {
curr.parent.rank--;
if (curr.marked) {
this.markedHeapNodesCounter--;
curr.marked = false;
}
if (curr.parent.child == curr) { // we should change the parent's child
if (curr.next == curr) { // curr do not have brothers
curr.parent.child = null;
} else { // curr have brothers
curr.parent.child = curr.next;
}
}
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
curr.next = curr;
curr.prev = curr;
curr.parent = null;
this.min.setNext(curr);
this.updateMin(curr);
this.numOfTrees++;
totalCuts++;
}
/*
*
*/
private void successiveLink(HeapNode curr) {
HeapNode[] buckets = this.toBuckets(curr);
this.min = this.fromBuckets(buckets);
}
/*
*
*/
private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null;
HeapNode tmpCurr;
while (curr != null) {
tmpCurr = curr;
curr = curr.next;
tmpCurr.next = tmpCurr;
tmpCurr.prev = tmpCurr;
while (buckets[tmpCurr.rank] != null) {
tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]);
buckets[tmpCurr.rank - 1] = null;
}
buckets[tmpCurr.rank] = tmpCurr;
}
return buckets;
}
/*
*
*/
private HeapNode fromBuckets(HeapNode[] buckets) {
HeapNode tmpMin = null;
this.numOfTrees = 0;
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] != null) {
this.numOfTrees++;
if (tmpMin == null) {
tmpMin = buckets[i];
tmpMin.next = tmpMin;
tmpMin.prev = tmpMin;
} else {
tmpMin.setNext(buckets[i]);
if (buckets[i].getKey() < tmpMin.getKey()) {
tmpMin = buckets[i];
}
}
}
}
return tmpMin;
}
/*
* link between two nodes (and their trees)
* defines the smaller node to be the parent
*/
private HeapNode link(HeapNode c1, HeapNode c2) {
if (c1.getKey() > c2.getKey()) {
HeapNode c3 = c1;
c1 = c2;
c2 = c3;
}
if (c1.child == null) {
c1.child = c2;
} else {
c1.child.setNext(c2);
}
c2.parent = c1;
c1.rank++;
totalLinks++;
return c1;
}
/**
* public class HeapNode
* each HeapNode belongs to a heap (Inner class)
*/
public class HeapNode {
public int key;
private int rank;
private boolean marked;
private HeapNode child;
private HeapNode next;
private HeapNode prev;
private HeapNode parent;
/*
* a constructor for a heapNode with key @param (key)
* prev == next == this
* parent == child == null
*/
public HeapNode(int key) {
this.key = key;
this.marked = false;
this.next = this;
this.prev = this;
}
/*
* returns the key of the node.
*/
public int getKey() {
return this.key;
}
/*
* checks whether the node is marked
* $ret = true if one child has been cut
*/
private boolean isMarked() {
return this.marked;
}
/*
* mark a node (after a child was cut)
* @inv root.mark() == false.
*/
private void mark() {
if (this.isRoot()) {
return;
} // check if the node is a root
this.marked = true;
}
/*
* add the node @param (newNext) to be between this and this.next
* works fine also if @param (newNext) does not "stands" alone
*/
private void setNext(HeapNode newNext) {
HeapNode tmpNext = this.next;
this.next = newNext;
this.next.prev.next = tmpNext;
tmpNext.prev = newNext.prev;
this.next.prev = this;
}
/*
* returns the next node to this node
*/
private HeapNode getNext() {
return this.next;
}
/*
* check if the node is a root
* root definition - this.parent == null (uppest in his tree)
*/
private boolean isRoot() {
return (this.parent == null);
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java | src/main/java/com/thealgorithms/datastructures/heaps/KthElementFinder.java |
package com.thealgorithms.datastructures.heaps;
import java.util.PriorityQueue;
/**
* This class provides methods to find the Kth largest or Kth smallest element
* in an array using heaps. It leverages a min-heap to find the Kth largest element
* and a max-heap to find the Kth smallest element efficiently.
*
* @author Hardvan
*/
public final class KthElementFinder {
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.
*
* @param nums the input array of integers
* @param k the desired Kth position (1-indexed, i.e., 1 means the largest element)
* @return the Kth largest element in the array
*/
public static int findKthLargest(int[] nums, int k) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>(k);
for (int num : nums) {
minHeap.offer(num);
if (minHeap.size() > k) {
minHeap.poll();
}
}
return minHeap.peek();
}
/**
* 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.
*
* @param nums the input array of integers
* @param k the desired Kth position (1-indexed, i.e., 1 means the smallest element)
* @return the Kth smallest element in the array
*/
public static int findKthSmallest(int[] nums, int k) {
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
for (int num : nums) {
maxHeap.offer(num);
if (maxHeap.size() > k) {
maxHeap.poll();
}
}
return maxHeap.peek();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java | src/main/java/com/thealgorithms/datastructures/heaps/MaxHeap.java | package com.thealgorithms.datastructures.heaps;
import java.util.ArrayList;
import java.util.List;
/**
* 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:
* <pre>
* List<HeapElement> elements = Arrays.asList(
* new HeapElement(5, "Five"),
* new HeapElement(2, "Two")
* );
* MaxHeap heap = new MaxHeap(elements);
* heap.insertElement(new HeapElement(7, "Seven"));
* HeapElement max = heap.getElement(); // Returns and removes the maximum element
* </pre>
*
* @author Nicolas Renard
*/
public class MaxHeap implements Heap {
/** The internal list that stores heap elements */
private final List<HeapElement> maxHeap;
/**
* Constructs a new MaxHeap from a list of elements.
* Null elements in the input list are ignored.
*
* @param listElements List of HeapElement objects to initialize the heap
* @throws IllegalArgumentException if the input list is null
*/
public MaxHeap(List<HeapElement> listElements) {
if (listElements == null) {
throw new IllegalArgumentException("Input list cannot be null");
}
maxHeap = new ArrayList<>();
// Safe initialization: directly add non-null elements first
for (HeapElement heapElement : listElements) {
if (heapElement != null) {
maxHeap.add(heapElement);
}
}
// Heapify the array bottom-up
for (int i = maxHeap.size() / 2; i >= 0; i--) {
heapifyDown(i + 1); // +1 because heapifyDown expects 1-based index
}
}
/**
* Maintains heap properties by moving an element down the heap.
* Similar to toggleDown but used specifically during initialization.
*
* @param elementIndex 1-based index of the element to heapify
*/
private void heapifyDown(int elementIndex) {
int largest = elementIndex - 1;
int leftChild = 2 * elementIndex - 1;
int rightChild = 2 * elementIndex;
if (leftChild < maxHeap.size() && maxHeap.get(leftChild).getKey() > maxHeap.get(largest).getKey()) {
largest = leftChild;
}
if (rightChild < maxHeap.size() && maxHeap.get(rightChild).getKey() > maxHeap.get(largest).getKey()) {
largest = rightChild;
}
if (largest != elementIndex - 1) {
HeapElement swap = maxHeap.get(elementIndex - 1);
maxHeap.set(elementIndex - 1, maxHeap.get(largest));
maxHeap.set(largest, swap);
heapifyDown(largest + 1);
}
}
/**
* Retrieves the element at the specified index without removing it.
* Note: The index is 1-based for consistency with heap operations.
*
* @param elementIndex 1-based index of the element to retrieve
* @return HeapElement at the specified index
* @throws IndexOutOfBoundsException if the index is invalid
*/
public HeapElement getElement(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]");
}
return maxHeap.get(elementIndex - 1);
}
/**
* Retrieves the key value of an element at the specified index.
*
* @param elementIndex 1-based index of the element
* @return double value representing the key
* @throws IndexOutOfBoundsException if the index is invalid
*/
private double getElementKey(int elementIndex) {
if ((elementIndex <= 0) || (elementIndex > maxHeap.size())) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]");
}
return maxHeap.get(elementIndex - 1).getKey();
}
/**
* Swaps two elements in the heap.
*
* @param index1 1-based index of first element
* @param index2 1-based index of second element
*/
private void swap(int index1, int index2) {
HeapElement temporaryElement = maxHeap.get(index1 - 1);
maxHeap.set(index1 - 1, maxHeap.get(index2 - 1));
maxHeap.set(index2 - 1, temporaryElement);
}
/**
* Moves an element up the heap until heap properties are satisfied.
* This operation is called after insertion to maintain heap properties.
*
* @param elementIndex 1-based index of the element to move up
*/
private void toggleUp(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
while (elementIndex > 1 && getElementKey((int) Math.floor(elementIndex / 2.0)) < key) {
swap(elementIndex, (int) Math.floor(elementIndex / 2.0));
elementIndex = (int) Math.floor(elementIndex / 2.0);
}
}
/**
* Moves an element down the heap until heap properties are satisfied.
* This operation is called after deletion to maintain heap properties.
*
* @param elementIndex 1-based index of the element to move down
*/
private void toggleDown(int elementIndex) {
double key = maxHeap.get(elementIndex - 1).getKey();
boolean wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1));
while (2 * elementIndex <= maxHeap.size() && wrongOrder) {
int largerChildIndex;
if (2 * elementIndex + 1 <= maxHeap.size() && getElementKey(elementIndex * 2 + 1) > getElementKey(elementIndex * 2)) {
largerChildIndex = 2 * elementIndex + 1;
} else {
largerChildIndex = 2 * elementIndex;
}
swap(elementIndex, largerChildIndex);
elementIndex = largerChildIndex;
wrongOrder = (2 * elementIndex <= maxHeap.size() && key < getElementKey(elementIndex * 2)) || (2 * elementIndex + 1 <= maxHeap.size() && key < getElementKey(elementIndex * 2 + 1));
}
}
/**
* Extracts and returns the maximum element from the heap.
*
* @return HeapElement with the highest key
* @throws EmptyHeapException if the heap is empty
*/
private HeapElement extractMax() throws EmptyHeapException {
if (maxHeap.isEmpty()) {
throw new EmptyHeapException("Cannot extract from an empty heap");
}
HeapElement result = maxHeap.getFirst();
deleteElement(1);
return result;
}
/**
* {@inheritDoc}
*/
@Override
public void insertElement(HeapElement element) {
if (element == null) {
throw new IllegalArgumentException("Cannot insert null element");
}
maxHeap.add(element);
toggleUp(maxHeap.size());
}
/**
* {@inheritDoc}
*/
@Override
public void deleteElement(int elementIndex) throws EmptyHeapException {
if (maxHeap.isEmpty()) {
throw new EmptyHeapException("Cannot delete from an empty heap");
}
if ((elementIndex > maxHeap.size()) || (elementIndex <= 0)) {
throw new IndexOutOfBoundsException("Index " + elementIndex + " is out of heap range [1, " + maxHeap.size() + "]");
}
// Replace with last element and remove last position
maxHeap.set(elementIndex - 1, maxHeap.getLast());
maxHeap.removeLast();
// No need to toggle if we just removed the last element
if (!maxHeap.isEmpty() && elementIndex <= maxHeap.size()) {
// Determine whether to toggle up or down
if (elementIndex > 1 && getElementKey(elementIndex) > getElementKey((int) Math.floor(elementIndex / 2.0))) {
toggleUp(elementIndex);
} else {
toggleDown(elementIndex);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public HeapElement getElement() throws EmptyHeapException {
return extractMax();
}
/**
* Returns the current size of the heap.
*
* @return number of elements in the heap
*/
public int size() {
return maxHeap.size();
}
/**
* Checks if the heap is empty.
*
* @return true if the heap contains no elements
*/
public boolean isEmpty() {
return maxHeap.isEmpty();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java | src/main/java/com/thealgorithms/datastructures/heaps/MedianFinder.java | package com.thealgorithms.datastructures.heaps;
import java.util.PriorityQueue;
/**
* This class maintains the median of a dynamically changing data stream using
* two heaps: a max-heap and a min-heap. The max-heap stores the smaller half
* of the numbers, and the min-heap stores the larger half.
* This data structure ensures that retrieving the median is efficient.
*
* 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<Integer> minHeap = new PriorityQueue<>();
private PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
/**
* Adds a new number to the data stream. The number is placed in the appropriate
* heap to maintain the balance between the two heaps.
*
* @param num the number to be added to the data stream
*/
public void addNum(int num) {
if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
maxHeap.offer(num);
} else {
minHeap.offer(num);
}
if (maxHeap.size() > minHeap.size() + 1) {
minHeap.offer(maxHeap.poll());
} else if (minHeap.size() > maxHeap.size()) {
maxHeap.offer(minHeap.poll());
}
}
/**
* Finds the median of the numbers added so far. If the total number of elements
* is even, the median is the average of the two middle elements. If odd, the
* median is the middle element from the max-heap.
*
* @return the median of the numbers in the data stream
*/
public double findMedian() {
if (maxHeap.size() == minHeap.size()) {
return (maxHeap.peek() + minHeap.peek()) / 2.0;
}
return maxHeap.peek();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java | src/main/java/com/thealgorithms/datastructures/heaps/HeapElement.java | package com.thealgorithms.datastructures.heaps;
/**
* Class representing an element in a heap.
*
* <p>
* A heap element contains two attributes: a key used for ordering in the heap
* (which can be of type int or double, either as primitive types or as wrapper objects)
* and an additional immutable object that can store any supplementary information the user desires.
* Note that using mutable objects may compromise the integrity of this information.
* </p>
*
* <p>
* The key attribute is used to determine the order of elements in the heap,
* while the additionalInfo attribute can carry user-defined data associated with the key.
* </p>
*
* <p>
* This class provides multiple constructors to accommodate various key types and includes
* methods to retrieve the key and additional information.
* </p>
*
* @author Nicolas Renard
*/
public class HeapElement {
private final double key;
private final Object additionalInfo;
// Constructors
/**
* Creates a HeapElement with the specified key and additional information.
*
* @param key the key of the element (primitive type double)
* @param info any immutable object containing additional information, may be null
*/
public HeapElement(double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* Creates a HeapElement with the specified key and additional information.
*
* @param key the key of the element (primitive type int)
* @param info any immutable object containing additional information, may be null
*/
public HeapElement(int key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* Creates a HeapElement with the specified key and additional information.
*
* @param key the key of the element (object type Integer)
* @param info any immutable object containing additional information, may be null
*/
public HeapElement(Integer key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* Creates a HeapElement with the specified key and additional information.
*
* @param key the key of the element (object type Double)
* @param info any immutable object containing additional information, may be null
*/
public HeapElement(Double key, Object info) {
this.key = key;
this.additionalInfo = info;
}
/**
* Creates a HeapElement with the specified key.
*
* @param key the key of the element (primitive type double)
*/
public HeapElement(double key) {
this.key = key;
this.additionalInfo = null;
}
/**
* Creates a HeapElement with the specified key.
*
* @param key the key of the element (primitive type int)
*/
public HeapElement(int key) {
this.key = key;
this.additionalInfo = null;
}
/**
* Creates a HeapElement with the specified key.
*
* @param key the key of the element (object type Integer)
*/
public HeapElement(Integer key) {
this.key = key;
this.additionalInfo = null;
}
/**
* Creates a HeapElement with the specified key.
*
* @param key the key of the element (object type Double)
*/
public HeapElement(Double key) {
this.key = key;
this.additionalInfo = null;
}
// Getters
/**
* Returns the object containing the additional information provided by the user.
*
* @return the additional information
*/
public Object getInfo() {
return additionalInfo;
}
/**
* Returns the key value of the element.
*
* @return the key of the element
*/
public double getKey() {
return key;
}
// Overridden object methods
/**
* Returns a string representation of the heap element.
*
* @return a string describing the key and additional information
*/
@Override
public String toString() {
return "Key: " + key + " - " + (additionalInfo != null ? additionalInfo.toString() : "No additional info");
}
/**
* @param o : an object to compare with the current element
* @return true if the keys on both elements are identical and the
* additional info objects are identical.
*/
@Override
public boolean equals(Object o) {
if (o instanceof HeapElement otherHeapElement) {
return this.key == otherHeapElement.key && (this.additionalInfo != null ? this.additionalInfo.equals(otherHeapElement.additionalInfo) : otherHeapElement.additionalInfo == null);
}
return false;
}
/**
* Returns a hash code value for the heap element.
*
* @return a hash code value for this heap element
*/
@Override
public int hashCode() {
int result = 31 * (int) key;
result += (additionalInfo != null) ? additionalInfo.hashCode() : 0;
return result;
}
public String getValue() {
return additionalInfo.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java | src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java | package com.thealgorithms.datastructures.heaps;
/**
* A MinPriorityQueue is a specialized data structure that maintains the
* min-heap property, where the smallest element has the highest priority.
*
* <p>In a min-priority queue, every parent node is less than or equal
* to its child nodes, which ensures that the smallest element can
* always be efficiently retrieved.</p>
*
* <p>Functions:</p>
* <ul>
* <li><b>insert(int key)</b>: Inserts a new key into the queue.</li>
* <li><b>delete()</b>: Removes and returns the highest priority value (the minimum).</li>
* <li><b>peek()</b>: Returns the highest priority value without removing it.</li>
* <li><b>isEmpty()</b>: Checks if the queue is empty.</li>
* <li><b>isFull()</b>: Checks if the queue is full.</li>
* <li><b>heapSort()</b>: Sorts the elements in ascending order.</li>
* <li><b>print()</b>: Prints the current elements in the queue.</li>
* </ul>
*/
public class MinPriorityQueue {
private final int[] heap;
private final int capacity;
private int size;
/**
* Initializes a new MinPriorityQueue with a specified capacity.
*
* @param c the maximum number of elements the queue can hold
*/
public MinPriorityQueue(int c) {
this.capacity = c;
this.size = 0;
this.heap = new int[c + 1];
}
/**
* Inserts a new key into the min-priority queue.
*
* @param key the value to be inserted
*/
public void insert(int key) {
if (this.isFull()) {
throw new IllegalStateException("MinPriorityQueue is full. Cannot insert new element.");
}
this.heap[this.size + 1] = key;
int k = this.size + 1;
while (k > 1) {
if (this.heap[k] < this.heap[k / 2]) {
int temp = this.heap[k];
this.heap[k] = this.heap[k / 2];
this.heap[k / 2] = temp;
}
k = k / 2;
}
this.size++;
}
/**
* Retrieves the highest priority value (the minimum) without removing it.
*
* @return the minimum value in the queue
* @throws IllegalStateException if the queue is empty
*/
public int peek() {
if (isEmpty()) {
throw new IllegalStateException("MinPriorityQueue is empty. Cannot peek.");
}
return this.heap[1];
}
/**
* Checks whether the queue is empty.
*
* @return true if the queue is empty, false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Checks whether the queue is full.
*
* @return true if the queue is full, false otherwise
*/
public boolean isFull() {
return size == capacity;
}
/**
* Prints the elements of the queue.
*/
public void print() {
for (int i = 1; i <= this.size; i++) {
System.out.print(this.heap[i] + " ");
}
System.out.println();
}
/**
* Sorts the elements in the queue using heap sort.
*/
public void heapSort() {
for (int i = 1; i <= this.size; i++) {
this.delete();
}
}
/**
* Reorders the heap after a deletion to maintain the heap property.
*/
private void sink() {
int k = 1;
while (2 * k <= this.size) {
int minIndex = k; // Assume current index is the minimum
if (2 * k <= this.size && this.heap[2 * k] < this.heap[minIndex]) {
minIndex = 2 * k; // Left child is smaller
}
if (2 * k + 1 <= this.size && this.heap[2 * k + 1] < this.heap[minIndex]) {
minIndex = 2 * k + 1; // Right child is smaller
}
if (minIndex == k) {
break; // No swap needed, heap property is satisfied
}
// Swap with the smallest child
int temp = this.heap[k];
this.heap[k] = this.heap[minIndex];
this.heap[minIndex] = temp;
k = minIndex; // Move down to the smallest child
}
}
/**
* Deletes and returns the highest priority value (the minimum) from the queue.
*
* @return the minimum value from the queue
* @throws IllegalStateException if the queue is empty
*/
public int delete() {
if (isEmpty()) {
throw new IllegalStateException("MinPriorityQueue is empty. Cannot delete.");
}
int min = this.heap[1];
this.heap[1] = this.heap[this.size]; // Move last element to the root
this.size--;
this.sink();
return min;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java | src/main/java/com/thealgorithms/datastructures/heaps/GenericHeap.java | package com.thealgorithms.datastructures.heaps;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A generic implementation of a max heap data structure.
*
* @param <T> the type of elements in this heap, must extend Comparable.
*/
public class GenericHeap<T extends Comparable<T>> {
private final ArrayList<T> data = new ArrayList<>();
private final HashMap<T, Integer> map = new HashMap<>();
/**
* Adds an item to the heap, maintaining the heap property.
*
* @param item the item to be added
*/
public void add(T item) {
if (item == null) {
throw new IllegalArgumentException("Cannot insert null into the heap.");
}
this.data.add(item);
map.put(item, this.data.size() - 1);
upHeapify(this.data.size() - 1);
}
/**
* Restores the heap property by moving the item at the given index upwards.
*
* @param ci the index of the current item
*/
private void upHeapify(int ci) {
int pi = (ci - 1) / 2;
if (ci > 0 && isLarger(this.data.get(ci), this.data.get(pi)) > 0) {
swap(pi, ci);
upHeapify(pi);
}
}
/**
* Returns the number of elements in the heap.
*
* @return the size of the heap
*/
public int size() {
return this.data.size();
}
/**
* Checks if the heap is empty.
*
* @return true if the heap is empty, false otherwise
*/
public boolean isEmpty() {
return this.size() == 0;
}
/**
* Removes and returns the maximum item from the heap.
*
* @return the maximum item
*/
public T remove() {
if (isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
this.swap(0, this.size() - 1);
T rv = this.data.remove(this.size() - 1);
map.remove(rv);
downHeapify(0);
return rv;
}
/**
* Restores the heap property by moving the item at the given index downwards.
*
* @param pi the index of the current item
*/
private void downHeapify(int pi) {
int lci = 2 * pi + 1;
int rci = 2 * pi + 2;
int mini = pi;
if (lci < this.size() && isLarger(this.data.get(lci), this.data.get(mini)) > 0) {
mini = lci;
}
if (rci < this.size() && isLarger(this.data.get(rci), this.data.get(mini)) > 0) {
mini = rci;
}
if (mini != pi) {
this.swap(pi, mini);
downHeapify(mini);
}
}
/**
* Retrieves the maximum item from the heap without removing it.
*
* @return the maximum item
*/
public T get() {
if (isEmpty()) {
throw new IllegalStateException("Heap is empty");
}
return this.data.getFirst();
}
/**
* Compares two items to determine their order.
*
* @param t the first item
* @param o the second item
* @return a positive integer if t is greater than o, negative if t is less, and zero if they are equal
*/
private int isLarger(T t, T o) {
return t.compareTo(o);
}
/**
* Swaps two items in the heap and updates their indices in the map.
*
* @param i index of the first item
* @param j index of the second item
*/
private void swap(int i, int j) {
T ith = this.data.get(i);
T jth = this.data.get(j);
this.data.set(i, jth);
this.data.set(j, ith);
map.put(ith, j);
map.put(jth, i);
}
/**
* Updates the priority of the specified item by restoring the heap property.
*
* @param item the item whose priority is to be updated
*/
public void updatePriority(T item) {
if (!map.containsKey(item)) {
throw new IllegalArgumentException("Item not found in the heap");
}
int index = map.get(item);
upHeapify(index);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/heaps/EmptyHeapException.java | src/main/java/com/thealgorithms/datastructures/heaps/EmptyHeapException.java | package com.thealgorithms.datastructures.heaps;
/**
* @author Nicolas Renard Exception to be thrown if the getElement method is
* used on an empty heap.
*/
@SuppressWarnings("serial")
public class EmptyHeapException extends Exception {
public EmptyHeapException(String message) {
super(message);
}
public EmptyHeapException(String message, Throwable cause) {
super(message, cause);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java | src/main/java/com/thealgorithms/datastructures/stacks/StackOfLinkedList.java | package com.thealgorithms.datastructures.stacks;
import java.util.NoSuchElementException;
/**
* A stack implementation using a singly linked list.
*
* <p>This class provides methods to push, pop, and peek elements in a Last-In-First-Out (LIFO) manner.
* It keeps track of the number of elements in the stack and allows checking if the stack is empty.
*
* <p>This implementation does not allow null elements to be pushed onto the stack.
*/
final class StackOfLinkedList {
private StackOfLinkedList() {
}
}
// A node class for the linked list
class Node {
public int data;
public Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
/**
* A class that implements a stack using a linked list.
*
* <p>This stack supports basic operations:
* <ul>
* <li>push: Adds an element to the top of the stack</li>
* <li>pop: Removes and returns the top element of the stack</li>
* <li>peek: Returns the top element without removing it</li>
* <li>isEmpty: Checks if the stack is empty</li>
* <li>getSize: Returns the current size of the stack</li>
* </ul>
*/
class LinkedListStack {
private Node head; // Top of the stack
private int size; // Number of elements in the stack
/**
* Initializes an empty stack.
*/
LinkedListStack() {
head = null;
size = 0;
}
/**
* Adds an element to the top of the stack.
*
* @param x the element to be added
* @return <tt>true</tt> if the element is added successfully
*/
public boolean push(int x) {
Node newNode = new Node(x);
newNode.next = head;
head = newNode;
size++;
return true;
}
/**
* Removes and returns the top element of the stack.
*
* @return the element at the top of the stack
* @throws NoSuchElementException if the stack is empty
*/
public int pop() {
if (size == 0) {
throw new NoSuchElementException("Empty stack. Nothing to pop");
}
Node destroy = head;
head = head.next;
int retValue = destroy.data;
destroy = null; // Help garbage collection
size--;
return retValue;
}
/**
* Returns the top element of the stack without removing it.
*
* @return the element at the top of the stack
* @throws NoSuchElementException if the stack is empty
*/
public int peek() {
if (size == 0) {
throw new NoSuchElementException("Empty stack. Nothing to peek");
}
return head.data;
}
@Override
public String toString() {
Node cur = head;
StringBuilder builder = new StringBuilder();
while (cur != null) {
builder.append(cur.data).append("->");
cur = cur.next;
}
return builder.replace(builder.length() - 2, builder.length(), "").toString(); // Remove the last "->"
}
/**
* Checks if the stack is empty.
*
* @return <tt>true</tt> if the stack is empty, <tt>false</tt> otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the current size of the stack.
*
* @return the number of elements in the stack
*/
public int getSize() {
return size;
}
/**
* Removes all elements from the stack.
*/
public void makeEmpty() {
head = null;
size = 0;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java | src/main/java/com/thealgorithms/datastructures/stacks/ReverseStack.java | package com.thealgorithms.datastructures.stacks;
import java.util.Stack;
/**
* Provides methods to reverse a stack using recursion.
*
* <p>This class includes methods to reverse the order of elements in a stack
* without using additional data structures. Elements are inserted at the bottom
* of the stack to achieve the reverse order.
*
* <p>Example usage:
* <pre>
* Stack<Integer> stack = new Stack<>();
* stack.push(1);
* stack.push(2);
* stack.push(3);
* ReverseStack.reverseStack(stack);
* </pre>
* After calling {@code reverseStack(stack)}, the stack's order is reversed.
*
* <p>This class is final and has a private constructor to prevent instantiation.
*
* @author Ishika Agarwal, 2021
*/
public final class ReverseStack {
private ReverseStack() {
}
/**
* Reverses the order of elements in the given stack using recursion.
* Steps:
* 1. Check if the stack is empty. If so, return.
* 2. Pop the top element from the stack.
* 3. Recursively reverse the remaining stack.
* 4. Insert the originally popped element at the bottom of the reversed stack.
*
* @param stack the stack to reverse; should not be null
*/
public static void reverseStack(Stack<Integer> stack) {
if (stack == null) {
throw new IllegalArgumentException("Stack cannot be null");
}
if (stack.isEmpty()) {
return;
}
int element = stack.pop();
reverseStack(stack);
insertAtBottom(stack, element);
}
/**
* Inserts the specified element at the bottom of the stack.
*
* <p>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.
* 3. Recursively insert the new element at the bottom of the stack.
* 4. Push the removed element back onto the stack.
*
* @param stack the stack in which to insert the element; should not be null
* @param element the element to insert at the bottom of the stack
*/
private static void insertAtBottom(Stack<Integer> stack, int element) {
if (stack.isEmpty()) {
stack.push(element);
return;
}
int topElement = stack.pop();
insertAtBottom(stack, element);
stack.push(topElement);
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/StackArrayList.java | src/main/java/com/thealgorithms/datastructures/stacks/StackArrayList.java | package com.thealgorithms.datastructures.stacks;
import java.util.ArrayList;
import java.util.EmptyStackException;
/**
* A stack implementation backed by an {@link ArrayList}, offering dynamic resizing
* and LIFO (Last-In-First-Out) behavior.
*
* <p>The stack grows dynamically as elements are added, and elements are removed
* in reverse order of their addition.
*
* @param <T> the type of elements stored in this stack
*/
public class StackArrayList<T> implements Stack<T> {
private final ArrayList<T> stack;
/**
* Constructs an empty stack.
*/
public StackArrayList() {
stack = new ArrayList<>();
}
/**
* Adds an element to the top of the stack.
*
* @param value the element to be added
*/
@Override
public void push(T value) {
stack.add(value);
}
/**
* Removes and returns the element from the top of the stack.
*
* @return the element removed from the top of the stack
* @throws EmptyStackException if the stack is empty
*/
@Override
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.removeLast();
}
/**
* Returns the element at the top of the stack without removing it.
*
* @return the top element of the stack
* @throws EmptyStackException if the stack is empty
*/
@Override
public T peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return stack.getLast();
}
/**
* Checks if the stack is empty.
*
* @return {@code true} if the stack is empty, {@code false} otherwise
*/
@Override
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* Empties the stack, removing all elements.
*/
@Override
public void makeEmpty() {
stack.clear();
}
/**
* Returns the number of elements in the stack.
*
* @return the current size of the stack
*/
@Override
public int size() {
return stack.size();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/Stack.java | src/main/java/com/thealgorithms/datastructures/stacks/Stack.java | package com.thealgorithms.datastructures.stacks;
/**
* A generic interface for Stack data structures.
*
* @param <T> the type of elements in this stack
*/
public interface Stack<T> {
/**
* Adds an element to the top of the stack.
*
* @param value The element to add.
*/
void push(T value);
/**
* Removes the element at the top of this stack and returns it.
*
* @return The element popped from the stack.
* @throws IllegalStateException if the stack is empty.
*/
T pop();
/**
* Returns the element at the top of this stack without removing it.
*
* @return The element at the top of this stack.
* @throws IllegalStateException if the stack is empty.
*/
T peek();
/**
* Tests if this stack is empty.
*
* @return {@code true} if this stack is empty; {@code false} otherwise.
*/
boolean isEmpty();
/**
* Returns the size of this stack.
*
* @return The number of elements in this stack.
*/
int size();
/**
* Removes all elements from this stack.
*/
void makeEmpty();
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java | src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java | package com.thealgorithms.datastructures.stacks;
/**
* A stack implementation using linked nodes, supporting unlimited size without an ArrayList.
*
* <p>Each node in the stack contains data of generic type {@code Item}, along with references
* to the next and previous nodes, supporting typical stack operations.
*
* <p>The stack follows a Last-In-First-Out (LIFO) order where elements added last are
* removed first. Supported operations include push, pop, and peek.
*
* @param <Item> the type of elements held in this stack
*/
public class NodeStack<Item> {
/**
* Node class representing each element in the stack.
*/
private class Node {
Item data;
Node previous;
Node(Item data) {
this.data = data;
this.previous = null;
}
}
private Node head; // Top node in the stack
private int size; // Number of elements in the stack
/**
* Constructs an empty NodeStack.
*/
public NodeStack() {
head = null;
size = 0;
}
/**
* Pushes an item onto the stack.
*
* @param item the item to be pushed onto the stack
*/
public void push(Item item) {
Node newNode = new Node(item);
newNode.previous = head;
head = newNode;
size++;
}
/**
* Removes and returns the item at the top of the stack.
*
* @return the item at the top of the stack, or {@code null} if the stack is empty
* @throws IllegalStateException if the stack is empty
*/
public Item pop() {
if (isEmpty()) {
throw new IllegalStateException("Cannot pop from an empty stack.");
}
Item data = head.data;
head = head.previous;
size--;
return data;
}
/**
* Returns the item at the top of the stack without removing it.
*
* @return the item at the top of the stack, or {@code null} if the stack is empty
* @throws IllegalStateException if the stack is empty
*/
public Item peek() {
if (isEmpty()) {
throw new IllegalStateException("Cannot peek from an empty stack.");
}
return head.data;
}
/**
* Checks whether the stack is empty.
*
* @return {@code true} if the stack has no elements, {@code false} otherwise
*/
public boolean isEmpty() {
return head == null;
}
/**
* Returns the number of elements currently in the stack.
*
* @return the size of the stack
*/
public int size() {
return size;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java | src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java | package com.thealgorithms.datastructures.stacks;
/**
* Implements a generic stack using an array.
*
* <p>This stack automatically resizes when necessary, growing to accommodate additional elements and
* shrinking to conserve memory when its size significantly decreases.
*
* <p>Elements are pushed and popped in LIFO (last-in, first-out) order, where the last element added
* is the first to be removed.
*
* @param <T> the type of elements in this stack
*/
public class StackArray<T> implements Stack<T> {
private static final int DEFAULT_CAPACITY = 10;
private int maxSize;
private T[] stackArray;
private int top;
/**
* Creates a stack with a default capacity.
*/
@SuppressWarnings("unchecked")
public StackArray() {
this(DEFAULT_CAPACITY);
}
/**
* Creates a stack with a specified initial capacity.
*
* @param size the initial capacity of the stack, must be greater than 0
* @throws IllegalArgumentException if size is less than or equal to 0
*/
@SuppressWarnings("unchecked")
public StackArray(int size) {
if (size <= 0) {
throw new IllegalArgumentException("Stack size must be greater than 0");
}
this.maxSize = size;
this.stackArray = (T[]) new Object[size];
this.top = -1;
}
/**
* Pushes an element onto the top of the stack. Resizes the stack if it is full.
*
* @param value the element to push
*/
@Override
public void push(T value) {
if (isFull()) {
resize(maxSize * 2);
}
stackArray[++top] = value;
}
/**
* Removes and returns the element from the top of the stack. Shrinks the stack if
* its size is below a quarter of its capacity, but not below the default capacity.
*
* @return the element removed from the top of the stack
* @throws IllegalStateException if the stack is empty
*/
@Override
public T pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty, cannot pop element");
}
T value = stackArray[top--];
if (top + 1 < maxSize / 4 && maxSize > DEFAULT_CAPACITY) {
resize(maxSize / 2);
}
return value;
}
/**
* Returns the element at the top of the stack without removing it.
*
* @return the top element of the stack
* @throws IllegalStateException if the stack is empty
*/
@Override
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty, cannot peek element");
}
return stackArray[top];
}
/**
* Resizes the internal array to a new capacity.
*
* @param newSize the new size of the stack array
*/
private void resize(int newSize) {
@SuppressWarnings("unchecked") T[] newArray = (T[]) new Object[newSize];
System.arraycopy(stackArray, 0, newArray, 0, top + 1);
stackArray = newArray;
maxSize = newSize;
}
/**
* Checks if the stack is full.
*
* @return true if the stack is full, false otherwise
*/
public boolean isFull() {
return top + 1 == maxSize;
}
/**
* Checks if the stack is empty.
*
* @return true if the stack is empty, false otherwise
*/
@Override
public boolean isEmpty() {
return top == -1;
}
/**
* Empties the stack, marking it as empty without deleting elements. Elements are
* overwritten on subsequent pushes.
*/
@Override
public void makeEmpty() {
top = -1;
}
/**
* Returns the number of elements currently in the stack.
*
* @return the size of the stack
*/
@Override
public int size() {
return top + 1;
}
/**
* Returns a string representation of the stack.
*
* @return a string representation of the stack
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("StackArray [");
for (int i = 0; i <= top; i++) {
sb.append(stackArray[i]);
if (i < top) {
sb.append(", ");
}
}
sb.append("]");
return sb.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Map.java | package com.thealgorithms.datastructures.hashmap.hashing;
public abstract class Map<Key, Value> {
abstract boolean put(Key key, Value value);
abstract Value get(Key key);
abstract boolean delete(Key key);
abstract Iterable<Key> keys();
abstract int size();
public boolean contains(Key key) {
return get(key) != null;
}
protected int hash(Key key, int size) {
return (key.hashCode() & Integer.MAX_VALUE) % size;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArrayList.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* A generic implementation of a hash map using an array list of linked lists for collision resolution.
* This class allows storage of key-value pairs with average-case constant time complexity for insertion,
* deletion, and retrieval operations.
*
* <p>
* The hash map uses separate chaining to handle collisions. Each bucket in the hash map is represented
* by a linked list that holds nodes containing key-value pairs. When multiple keys hash to the same index,
* they are stored in the same linked list.
* </p>
*
* <p>
* The hash map automatically resizes itself when the load factor exceeds 0.5. The load factor is defined
* as the ratio of the number of entries to the number of buckets. When resizing occurs, all existing entries
* are rehashed and inserted into the new buckets.
* </p>
*
* @param <K> the type of keys maintained by this hash map
* @param <V> the type of mapped values
*/
public class GenericHashMapUsingArrayList<K, V> {
private ArrayList<LinkedList<Node>> buckets; // Array list of buckets (linked lists)
private int size; // Number of key-value pairs in the hash map
/**
* Constructs a new empty hash map with an initial capacity of 10 buckets.
*/
public GenericHashMapUsingArrayList() {
buckets = new ArrayList<>();
for (int i = 0; i < 10; i++) {
buckets.add(new LinkedList<>());
}
size = 0;
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is replaced.
*
* @param key the key with which the specified value is to be associated
* @param value the value to be associated with the specified key
*/
public void put(K key, V value) {
int hash = Math.abs(key.hashCode() % buckets.size());
LinkedList<Node> nodes = buckets.get(hash);
for (Node node : nodes) {
if (node.key.equals(key)) {
node.val = value;
return;
}
}
nodes.add(new Node(key, value));
size++;
// Load factor threshold for resizing
float loadFactorThreshold = 0.5f;
if ((float) size / buckets.size() > loadFactorThreshold) {
reHash();
}
}
/**
* Resizes the hash map by doubling the number of buckets and rehashing existing entries.
*/
private void reHash() {
ArrayList<LinkedList<Node>> oldBuckets = buckets;
buckets = new ArrayList<>();
size = 0;
for (int i = 0; i < oldBuckets.size() * 2; i++) {
buckets.add(new LinkedList<>());
}
for (LinkedList<Node> nodes : oldBuckets) {
for (Node node : nodes) {
put(node.key, node.val);
}
}
}
/**
* Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the value associated with the specified key, or null if no mapping exists
*/
public V get(K key) {
int hash = Math.abs(key.hashCode() % buckets.size());
LinkedList<Node> nodes = buckets.get(hash);
for (Node node : nodes) {
if (node.key.equals(key)) {
return node.val;
}
}
return null;
}
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key the key whose mapping is to be removed from the map
*/
public void remove(K key) {
int hash = Math.abs(key.hashCode() % buckets.size());
LinkedList<Node> nodes = buckets.get(hash);
Node target = null;
for (Node node : nodes) {
if (node.key.equals(key)) {
target = node;
break;
}
}
if (target != null) {
nodes.remove(target);
size--;
}
}
/**
* Returns true if this map contains a mapping for the specified key.
*
* @param key the key whose presence in this map is to be tested
* @return true if this map contains a mapping for the specified key
*/
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* Returns the number of key-value pairs in this map.
*
* @return the number of key-value pairs
*/
public int size() {
return this.size;
}
/**
* Returns a string representation of the map, containing all key-value pairs.
*
* @return a string representation of the map
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{");
for (LinkedList<Node> nodes : buckets) {
for (Node node : nodes) {
builder.append(node.key);
builder.append(" : ");
builder.append(node.val);
builder.append(", ");
}
}
// Remove trailing comma and space if there are any elements
if (builder.length() > 1) {
builder.setLength(builder.length() - 2);
}
builder.append("}");
return builder.toString();
}
/**
* A private inner class representing a key-value pair (node) in the hash map.
*/
private class Node {
K key;
V val;
/**
* Constructs a new Node with the specified key and value.
*
* @param key the key of the key-value pair
* @param val the value of the key-value pair
*/
Node(K key, V val) {
this.key = key;
this.val = val;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/ImmutableHashMap.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/ImmutableHashMap.java | package com.thealgorithms.datastructures.hashmap.hashing;
/**
* Immutable HashMap implementation using separate chaining.
*
* <p>This HashMap does not allow modification of existing instances.
* Any update operation returns a new ImmutableHashMap.
*
* @param <K> key type
* @param <V> value type
*/
public final class ImmutableHashMap<K, V> {
private static final int DEFAULT_CAPACITY = 16;
private final Node<K, V>[] table;
private final int size;
/**
* Private constructor to enforce immutability.
*/
private ImmutableHashMap(Node<K, V>[] table, int size) {
this.table = table;
this.size = size;
}
/**
* Creates an empty ImmutableHashMap.
*
* @param <K> key type
* @param <V> value type
* @return empty ImmutableHashMap
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public static <K, V> ImmutableHashMap<K, V> empty() {
Node<K, V>[] table = (Node<K, V>[]) new Node[DEFAULT_CAPACITY];
return new ImmutableHashMap<>(table, 0);
}
/**
* Returns a new ImmutableHashMap with the given key-value pair added.
*
* @param key key to add
* @param value value to associate
* @return new ImmutableHashMap instance
*/
public ImmutableHashMap<K, V> put(K key, V value) {
Node<K, V>[] newTable = table.clone();
int index = hash(key);
newTable[index] = new Node<>(key, value, newTable[index]);
return new ImmutableHashMap<>(newTable, size + 1);
}
/**
* Retrieves the value associated with the given key.
*
* @param key key to search
* @return value if found, otherwise null
*/
public V get(K key) {
int index = hash(key);
Node<K, V> current = table[index];
while (current != null) {
if ((key == null && current.key == null) || (key != null && key.equals(current.key))) {
return current.value;
}
current = current.next;
}
return null;
}
/**
* Checks whether the given key exists in the map.
*
* @param key key to check
* @return true if key exists, false otherwise
*/
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* Returns the number of key-value pairs.
*
* @return size of the map
*/
public int size() {
return size;
}
/**
* Computes hash index for a given key.
*/
private int hash(K key) {
return key == null ? 0 : (key.hashCode() & Integer.MAX_VALUE) % table.length;
}
/**
* Node class for separate chaining.
*/
private static final class Node<K, V> {
private final K key;
private final V value;
private final Node<K, V> next;
private Node(K key, V value, Node<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/LinearProbingHashMap.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.ArrayList;
/**
* This class implements a hash table using linear probing to resolve collisions.
* Linear probing is a collision resolution method where each slot in the hash table is checked in a sequential manner
* until an empty slot is found.
*
* <p>
* The class allows for storing key-value pairs, where both the key and value are generic types.
* The key must be of a type that implements the Comparable interface to ensure that the keys can be compared for sorting.
* </p>
*
* <p>
* This implementation supports basic operations such as:
* <ul>
* <li><b>put(Key key, Value value)</b>: Adds a key-value pair to the hash table. If the key already exists, its value is updated.</li>
* <li><b>get(Key key)</b>: Retrieves the value associated with the given key.</li>
* <li><b>delete(Key key)</b>: Removes the key and its associated value from the hash table.</li>
* <li><b>contains(Key key)</b>: Checks if the hash table contains a given key.</li>
* <li><b>size()</b>: Returns the number of key-value pairs in the hash table.</li>
* <li><b>keys()</b>: Returns an iterable collection of keys stored in the hash table.</li>
* </ul>
* </p>
*
* <p>
* The internal size of the hash table is automatically resized when the load factor exceeds 0.5 or falls below 0.125,
* ensuring efficient space utilization.
* </p>
*
* @see <a href="https://en.wikipedia.org/wiki/Linear_probing">Linear Probing Hash Table</a>
*
* @param <Key> the type of keys maintained by this map
* @param <Value> the type of mapped values
*/
@SuppressWarnings("rawtypes")
public class LinearProbingHashMap<Key extends Comparable<Key>, Value> extends Map<Key, Value> {
private int hsize; // size of the hash table
private Key[] keys; // array to store keys
private Value[] values; // array to store values
private int size; // number of elements in the hash table
// Default constructor initializes the table with a default size of 16
public LinearProbingHashMap() {
this(16);
}
@SuppressWarnings("unchecked")
// Constructor to initialize the hash table with a specified size
public LinearProbingHashMap(int size) {
this.hsize = size;
keys = (Key[]) new Comparable[size];
values = (Value[]) new Object[size];
}
@Override
public boolean put(Key key, Value value) {
if (key == null) {
return false;
}
if (size > hsize / 2) {
resize(2 * hsize);
}
int keyIndex = hash(key, hsize);
for (; keys[keyIndex] != null; keyIndex = increment(keyIndex)) {
if (key.equals(keys[keyIndex])) {
values[keyIndex] = value;
return true;
}
}
keys[keyIndex] = key;
values[keyIndex] = value;
size++;
return true;
}
@Override
public Value get(Key key) {
if (key == null) {
return null;
}
for (int i = hash(key, hsize); keys[i] != null; i = increment(i)) {
if (key.equals(keys[i])) {
return values[i];
}
}
return null;
}
@Override
public boolean delete(Key key) {
if (key == null || !contains(key)) {
return false;
}
int i = hash(key, hsize);
while (!key.equals(keys[i])) {
i = increment(i);
}
keys[i] = null;
values[i] = null;
i = increment(i);
while (keys[i] != null) {
// Save the key and value for rehashing
Key keyToRehash = keys[i];
Value valToRehash = values[i];
keys[i] = null;
values[i] = null;
size--;
put(keyToRehash, valToRehash);
i = increment(i);
}
size--;
if (size > 0 && size <= hsize / 8) {
resize(hsize / 2);
}
return true;
}
@Override
public boolean contains(Key key) {
return get(key) != null;
}
@Override
int size() {
return size;
}
@Override
Iterable<Key> keys() {
ArrayList<Key> listOfKeys = new ArrayList<>(size);
for (int i = 0; i < hsize; i++) {
if (keys[i] != null) {
listOfKeys.add(keys[i]);
}
}
listOfKeys.sort(Comparable::compareTo);
return listOfKeys;
}
private int increment(int i) {
return (i + 1) % hsize;
}
private void resize(int newSize) {
LinearProbingHashMap<Key, Value> tmp = new LinearProbingHashMap<>(newSize);
for (int i = 0; i < hsize; i++) {
if (keys[i] != null) {
tmp.put(keys[i], values[i]);
}
}
this.keys = tmp.keys;
this.values = tmp.values;
this.hsize = newSize;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MainCuckooHashing.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.Scanner;
public final class MainCuckooHashing {
private MainCuckooHashing() {
}
public static void main(String[] args) {
int choice;
int key;
HashMapCuckooHashing h = new HashMapCuckooHashing(7);
Scanner scan = new Scanner(System.in);
while (true) {
System.out.println("_________________________");
System.out.println("Enter your Choice :");
System.out.println("1. Add Key");
System.out.println("2. Delete Key");
System.out.println("3. Print Table");
System.out.println("4. Exit");
System.out.println("5. Search and print key index");
System.out.println("6. Check load factor");
System.out.println("7. Rehash Current Table");
choice = scan.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the Key: ");
key = scan.nextInt();
h.insertKey2HashTable(key);
break;
case 2:
System.out.println("Enter the Key delete: ");
key = scan.nextInt();
h.deleteKeyFromHashTable(key);
break;
case 3:
System.out.println("Print table:\n");
h.displayHashtable();
break;
case 4:
scan.close();
return;
case 5:
System.out.println("Enter the Key to find and print: ");
key = scan.nextInt();
System.out.println("Key: " + key + " is at index: " + h.findKeyInTable(key) + "\n");
break;
case 6:
System.out.printf("Load factor is: %.2f%n", h.checkLoadFactor());
break;
case 7:
h.reHashTableIncreasesTableSize();
break;
default:
throw new IllegalArgumentException("Unexpected value: " + choice);
}
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/GenericHashMapUsingArray.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.LinkedList;
/**
* A generic implementation of a hash map using an array of linked lists for collision resolution.
* This class provides a way to store key-value pairs efficiently, allowing for average-case
* constant time complexity for insertion, deletion, and retrieval operations.
*
* <p>
* The hash map uses separate chaining for collision resolution. Each bucket in the hash map is a
* linked list that stores nodes containing key-value pairs. When a collision occurs (i.e., when
* two keys hash to the same index), the new key-value pair is simply added to the corresponding
* linked list.
* </p>
*
* <p>
* The hash map automatically resizes itself when the load factor exceeds 0.75. The load factor is
* defined as the ratio of the number of entries to the number of buckets. When resizing occurs,
* all existing entries are rehashed and inserted into the new buckets.
* </p>
*
* @param <K> the type of keys maintained by this hash map
* @param <V> the type of mapped values
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public class GenericHashMapUsingArray<K, V> {
private int size; // Total number of key-value pairs
private LinkedList<Node>[] buckets; // Array of linked lists (buckets) for storing entries
/**
* Constructs a new empty hash map with an initial capacity of 16.
*/
public GenericHashMapUsingArray() {
initBuckets(16);
size = 0;
}
/**
* Initializes the buckets for the hash map with the specified number of buckets.
*
* @param n the number of buckets to initialize
*/
private void initBuckets(int n) {
buckets = new LinkedList[n];
for (int i = 0; i < buckets.length; i++) {
buckets[i] = new LinkedList<>();
}
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old value is replaced.
*
* @param key the key with which the specified value is to be associated
* @param value the value to be associated with the specified key
*/
public void put(K key, V value) {
int bucketIndex = hashFunction(key);
LinkedList<Node> nodes = buckets[bucketIndex];
// Update existing key's value if present
for (Node node : nodes) {
if (node.key.equals(key)) {
node.value = value;
return;
}
}
// Insert new key-value pair
nodes.add(new Node(key, value));
size++;
// Check if rehashing is needed
// Load factor threshold for resizing
float loadFactorThreshold = 0.75f;
if ((float) size / buckets.length > loadFactorThreshold) {
reHash();
}
}
/**
* Returns the index of the bucket in which the key would be stored.
*
* @param key the key whose bucket index is to be computed
* @return the bucket index
*/
private int hashFunction(K key) {
return Math.floorMod(key.hashCode(), buckets.length);
}
/**
* Rehashes the map by doubling the number of buckets and re-inserting all entries.
*/
private void reHash() {
LinkedList<Node>[] oldBuckets = buckets;
initBuckets(oldBuckets.length * 2);
this.size = 0;
for (LinkedList<Node> nodes : oldBuckets) {
for (Node node : nodes) {
put(node.key, node.value);
}
}
}
/**
* Removes the mapping for the specified key from this map if present.
*
* @param key the key whose mapping is to be removed from the map
*/
public void remove(K key) {
int bucketIndex = hashFunction(key);
LinkedList<Node> nodes = buckets[bucketIndex];
Node target = null;
for (Node node : nodes) {
if (node.key.equals(key)) {
target = node;
break;
}
}
if (target != null) {
nodes.remove(target);
size--;
}
}
/**
* Returns the number of key-value pairs in this map.
*
* @return the number of key-value pairs
*/
public int size() {
return this.size;
}
/**
* Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
*
* @param key the key whose associated value is to be returned
* @return the value associated with the specified key, or null if no mapping exists
*/
public V get(K key) {
int bucketIndex = hashFunction(key);
LinkedList<Node> nodes = buckets[bucketIndex];
for (Node node : nodes) {
if (node.key.equals(key)) {
return node.value;
}
}
return null;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("{");
for (LinkedList<Node> nodes : buckets) {
for (Node node : nodes) {
builder.append(node.key);
builder.append(" : ");
builder.append(node.value);
builder.append(", ");
}
}
// Remove trailing comma and space
if (builder.length() > 1) {
builder.setLength(builder.length() - 2);
}
builder.append("}");
return builder.toString();
}
/**
* Returns true if this map contains a mapping for the specified key.
*
* @param key the key whose presence in this map is to be tested
* @return true if this map contains a mapping for the specified key
*/
public boolean containsKey(K key) {
return get(key) != null;
}
/**
* A private class representing a key-value pair (node) in the hash map.
*/
public class Node {
K key;
V value;
/**
* Constructs a new Node with the specified key and value.
*
* @param key the key of the key-value pair
* @param value the value of the key-value pair
*/
public Node(K key, V value) {
this.key = key;
this.value = value;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/Intersection.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The {@code Intersection} class provides a method to compute the intersection of two integer arrays.
* <p>
* This intersection includes duplicate values — meaning elements are included in the result
* as many times as they appear in both arrays (i.e., multiset intersection).
* </p>
*
* <p>
* The algorithm uses a {@link java.util.HashMap} to count occurrences of elements in the first array,
* then iterates through the second array to collect common elements based on these counts.
* </p>
*
* <p>
* Example usage:
* <pre>{@code
* int[] array1 = {1, 2, 2, 1};
* int[] array2 = {2, 2};
* List<Integer> result = Intersection.intersection(array1, array2); // result: [2, 2]
* }</pre>
* </p>
*
* <p>
* Note: The order of elements in the returned list depends on the order in the second input array.
* </p>
*/
public final class Intersection {
private Intersection() {
// Utility class; prevent instantiation
}
/**
* 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.
*
* @param arr1 the first array of integers
* @param arr2 the second array of integers
* @return a list containing the intersection of the two arrays (with duplicates),
* or an empty list if either array is null or empty
*/
public static List<Integer> intersection(int[] arr1, int[] arr2) {
if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) {
return Collections.emptyList();
}
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : arr1) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
}
List<Integer> result = new ArrayList<>();
for (int num : arr2) {
if (countMap.getOrDefault(num, 0) > 0) {
result.add(num);
countMap.computeIfPresent(num, (k, v) -> v - 1);
}
}
return result;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/MajorityElement.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides a method to find the majority element(s) in an array of integers.
* A majority element is defined as an element that appears at least ⌊n/2⌋ times,
* where n is the length of the array. If multiple elements qualify as majority elements,
* they are all returned in a list.
*/
public final class MajorityElement {
private MajorityElement() {
}
/**
* Returns a list of majority element(s) from the given array of integers.
*
* @param nums an array of integers
* @return a list containing the majority element(s); returns an empty list if none exist or input is null/empty
*/
public static List<Integer> majority(int[] nums) {
if (nums == null || nums.length == 0) {
return Collections.emptyList();
}
Map<Integer, Integer> numToCount = new HashMap<>();
for (final var num : nums) {
numToCount.merge(num, 1, Integer::sum);
}
List<Integer> majorityElements = new ArrayList<>();
for (final var entry : numToCount.entrySet()) {
if (entry.getValue() >= nums.length / 2) {
majorityElements.add(entry.getKey());
}
}
return majorityElements;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java | package com.thealgorithms.datastructures.hashmap.hashing;
import java.util.Objects;
/**
* This class implements a hash table using Cuckoo Hashing.
* Cuckoo hashing is a type of open-addressing hash table that resolves collisions
* by relocating existing keys. It utilizes two hash functions to minimize collisions
* and automatically resizes the table when the load factor exceeds 0.7.
*
* For more information on cuckoo hashing, refer to
* <a href="https://en.wikipedia.org/wiki/Cuckoo_hashing">this Wikipedia page</a>.
*/
public class HashMapCuckooHashing {
private int tableSize; // Size of the hash table
private Integer[] buckets; // Array representing the hash table
private final Integer emptySlot; // Placeholder for deleted slots
private int size; // Number of elements in the hash table
private int thresh; // Threshold for detecting infinite loops during insertion
/**
* Constructs a HashMapCuckooHashing object with the specified initial table size.
*
* @param tableSize the initial size of the hash map
*/
public HashMapCuckooHashing(int tableSize) {
this.buckets = new Integer[tableSize];
this.tableSize = tableSize;
this.emptySlot = Integer.MIN_VALUE;
this.size = 0;
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
}
/**
* Computes the first hash index for a given key using the modulo operation.
*
* @param key the key for which the hash index is computed
* @return an integer index corresponding to the key
*/
public int hashFunction1(int key) {
int hash = key % tableSize;
if (hash < 0) {
hash += tableSize;
}
return hash;
}
/**
* Computes the second hash index for a given key using integer division.
*
* @param key the key for which the hash index is computed
* @return an integer index corresponding to the key
*/
public int hashFunction2(int key) {
int hash = key / tableSize;
hash %= tableSize;
if (hash < 0) {
hash += tableSize;
}
return hash;
}
/**
* Inserts a key into the hash table using cuckoo hashing.
* If the target bucket is occupied, it relocates the existing key and attempts to insert
* it into its alternate location. If the insertion process exceeds the threshold,
* the table is resized.
*
* @param key the key to be inserted into the hash table
* @throws IllegalArgumentException if the key already exists in the table
*/
public void insertKey2HashTable(int key) {
Integer wrappedInt = key;
Integer temp;
int hash;
int loopCounter = 0;
if (isFull()) {
System.out.println("Hash table is full, lengthening & rehashing table");
reHashTableIncreasesTableSize();
}
if (checkTableContainsKey(key)) {
throw new IllegalArgumentException("Key already exists; duplicates are not allowed.");
}
while (loopCounter <= thresh) {
loopCounter++;
hash = hashFunction1(key);
if ((buckets[hash] == null) || Objects.equals(buckets[hash], emptySlot)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
return;
}
temp = buckets[hash];
buckets[hash] = wrappedInt;
wrappedInt = temp;
hash = hashFunction2(temp);
if (Objects.equals(buckets[hash], emptySlot)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
return;
} else if (buckets[hash] == null) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
return;
}
temp = buckets[hash];
buckets[hash] = wrappedInt;
wrappedInt = temp;
}
System.out.println("Infinite loop occurred, lengthening & rehashing table");
reHashTableIncreasesTableSize();
insertKey2HashTable(key);
}
/**
* Rehashes the current table to a new size (double the current size) and reinserts existing keys.
*/
public void reHashTableIncreasesTableSize() {
HashMapCuckooHashing newT = new HashMapCuckooHashing(tableSize * 2);
for (int i = 0; i < tableSize; i++) {
if (buckets[i] != null && !Objects.equals(buckets[i], emptySlot)) {
newT.insertKey2HashTable(this.buckets[i]);
}
}
this.tableSize *= 2;
this.buckets = newT.buckets;
this.thresh = (int) (Math.log(tableSize) / Math.log(2)) + 2;
}
/**
* Deletes a key from the hash table, marking its position as available.
*
* @param key the key to be deleted from the hash table
* @throws IllegalArgumentException if the table is empty or if the key is not found
*/
public void deleteKeyFromHashTable(int key) {
Integer wrappedInt = key;
int hash = hashFunction1(key);
if (isEmpty()) {
throw new IllegalArgumentException("Table is empty, cannot delete.");
}
if (Objects.equals(buckets[hash], wrappedInt)) {
buckets[hash] = emptySlot;
size--;
return;
}
hash = hashFunction2(key);
if (Objects.equals(buckets[hash], wrappedInt)) {
buckets[hash] = emptySlot;
size--;
return;
}
throw new IllegalArgumentException("Key " + key + " not found in the table.");
}
/**
* Displays the hash table contents, bucket by bucket.
*/
public void displayHashtable() {
for (int i = 0; i < tableSize; i++) {
if ((buckets[i] == null) || Objects.equals(buckets[i], emptySlot)) {
System.out.println("Bucket " + i + ": Empty");
} else {
System.out.println("Bucket " + i + ": " + buckets[i].toString());
}
}
System.out.println();
}
/**
* Finds the index of a given key in the hash table.
*
* @param key the key to be found
* @return the index where the key is located
* @throws IllegalArgumentException if the table is empty or the key is not found
*/
public int findKeyInTable(int key) {
Integer wrappedInt = key;
int hash = hashFunction1(key);
if (isEmpty()) {
throw new IllegalArgumentException("Table is empty; cannot find keys.");
}
if (Objects.equals(buckets[hash], wrappedInt)) {
return hash;
}
hash = hashFunction2(key);
if (!Objects.equals(buckets[hash], wrappedInt)) {
throw new IllegalArgumentException("Key " + key + " not found in the table.");
} else {
return hash;
}
}
/**
* Checks if the given key is present in the hash table.
*
* @param key the key to be checked
* @return true if the key exists, false otherwise
*/
public boolean checkTableContainsKey(int key) {
return ((buckets[hashFunction1(key)] != null && buckets[hashFunction1(key)].equals(key)) || (buckets[hashFunction2(key)] != null && buckets[hashFunction2(key)].equals(key)));
}
/**
* Checks the load factor of the hash table. If the load factor exceeds 0.7,
* the table is resized to prevent further collisions.
*
* @return the current load factor of the hash table
*/
public double checkLoadFactor() {
double factor = (double) size / tableSize;
if (factor > .7) {
System.out.printf("Load factor is %.2f, rehashing table.%n", factor);
reHashTableIncreasesTableSize();
}
return factor;
}
/**
* Checks if the hash map is full.
*
* @return true if the hash map is full, false otherwise
*/
public boolean isFull() {
for (int i = 0; i < tableSize; i++) {
if (buckets[i] == null || Objects.equals(buckets[i], emptySlot)) {
return false;
}
}
return true;
}
/**
* Checks if the hash map is empty.
*
* @return true if the hash map is empty, false otherwise
*/
public boolean isEmpty() {
for (int i = 0; i < tableSize; i++) {
if (buckets[i] != null) {
return false;
}
}
return true;
}
/**
* Returns the current number of keys in the hash table.
*
* @return the number of keys present in the hash table
*/
public int getNumberOfKeysInTable() {
return size;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java | src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMap.java | package com.thealgorithms.datastructures.hashmap.hashing;
/**
* A generic HashMap implementation that uses separate chaining with linked lists
* to handle collisions. The class supports basic operations such as insert, delete,
* and search, as well as displaying the contents of the hash map.
*
* @param <K> the type of keys maintained by this map
* @param <V> the type of mapped values
*/
@SuppressWarnings("rawtypes")
public class HashMap<K, V> {
private final int hashSize;
private final LinkedList<K, V>[] buckets;
/**
* Constructs a HashMap with the specified hash size.
*
* @param hashSize the number of buckets in the hash map
*/
@SuppressWarnings("unchecked")
public HashMap(int hashSize) {
this.hashSize = hashSize;
// Safe to suppress warning because we are creating an array of generic type
this.buckets = new LinkedList[hashSize];
for (int i = 0; i < hashSize; i++) {
buckets[i] = new LinkedList<>();
}
}
/**
* Computes the hash code for the specified key.
* Null keys are hashed to bucket 0.
*
* @param key the key for which the hash code is to be computed
* @return the hash code corresponding to the key
*/
private int computeHash(K key) {
if (key == null) {
return 0; // Use a special bucket (e.g., bucket 0) for null keys
}
int hash = key.hashCode() % hashSize;
return hash < 0 ? hash + hashSize : hash;
}
/**
* Inserts the specified key-value pair into the hash map.
* If the key already exists, the value is updated.
*
* @param key the key to be inserted
* @param value the value to be associated with the key
*/
public void insert(K key, V value) {
int hash = computeHash(key);
buckets[hash].insert(key, value);
}
/**
* Deletes the key-value pair associated with the specified key from the hash map.
*
* @param key the key whose key-value pair is to be deleted
*/
public void delete(K key) {
int hash = computeHash(key);
buckets[hash].delete(key);
}
/**
* Searches for the value associated with the specified key in the hash map.
*
* @param key the key whose associated value is to be returned
* @return the value associated with the specified key, or null if the key does not exist
*/
public V search(K key) {
int hash = computeHash(key);
Node<K, V> node = buckets[hash].findKey(key);
return node != null ? node.getValue() : null;
}
/**
* Displays the contents of the hash map, showing each bucket and its key-value pairs.
*/
public void display() {
for (int i = 0; i < hashSize; i++) {
System.out.printf("Bucket %d: %s%n", i, buckets[i].display());
}
}
/**
* Clears the contents of the hash map by reinitializing each bucket.
*/
public void clear() {
for (int i = 0; i < hashSize; i++) {
buckets[i] = new LinkedList<>();
}
}
/**
* Gets the number of key-value pairs in the hash map.
*
* @return the number of key-value pairs in the hash map
*/
public int size() {
int size = 0;
for (int i = 0; i < hashSize; i++) {
size += buckets[i].isEmpty() ? 0 : 1;
}
return size;
}
/**
* A nested static class that represents a linked list used for separate chaining in the hash map.
*
* @param <K> the type of keys maintained by this linked list
* @param <V> the type of mapped values
*/
public static class LinkedList<K, V> {
private Node<K, V> head;
/**
* Inserts the specified key-value pair into the linked list.
* If the linked list is empty, the pair becomes the head.
* Otherwise, the pair is added to the end of the list.
*
* @param key the key to be inserted
* @param value the value to be associated with the key
*/
public void insert(K key, V value) {
Node<K, V> existingNode = findKey(key);
if (existingNode != null) {
existingNode.setValue(value); // Update the value, even if it's null
} else {
if (isEmpty()) {
head = new Node<>(key, value);
} else {
Node<K, V> temp = findEnd(head);
temp.setNext(new Node<>(key, value));
}
}
}
/**
* Finds the last node in the linked list.
*
* @param node the starting node
* @return the last node in the linked list
*/
private Node<K, V> findEnd(Node<K, V> node) {
while (node.getNext() != null) {
node = node.getNext();
}
return node;
}
/**
* Finds the node associated with the specified key in the linked list.
*
* @param key the key to search for
* @return the node associated with the specified key, or null if not found
*/
public Node<K, V> findKey(K key) {
Node<K, V> temp = head;
while (temp != null) {
if ((key == null && temp.getKey() == null) || (temp.getKey() != null && temp.getKey().equals(key))) {
return temp;
}
temp = temp.getNext();
}
return null;
}
/**
* Deletes the node associated with the specified key from the linked list.
* Handles the case where the key could be null.
*
* @param key the key whose associated node is to be deleted
*/
public void delete(K key) {
if (isEmpty()) {
return;
}
// Handle the case where the head node has the key to delete
if ((key == null && head.getKey() == null) || (head.getKey() != null && head.getKey().equals(key))) {
head = head.getNext();
return;
}
// Traverse the list to find and delete the node
Node<K, V> current = head;
while (current.getNext() != null) {
if ((key == null && current.getNext().getKey() == null) || (current.getNext().getKey() != null && current.getNext().getKey().equals(key))) {
current.setNext(current.getNext().getNext());
return;
}
current = current.getNext();
}
}
/**
* Displays the contents of the linked list as a string.
*
* @return a string representation of the linked list
*/
public String display() {
return display(head);
}
/**
* Constructs a string representation of the linked list non-recursively.
*
* @param node the starting node
* @return a string representation of the linked list starting from the given node
*/
private String display(Node<K, V> node) {
StringBuilder sb = new StringBuilder();
while (node != null) {
sb.append(node.getKey()).append("=").append(node.getValue());
node = node.getNext();
if (node != null) {
sb.append(" -> ");
}
}
return sb.toString().isEmpty() ? "null" : sb.toString();
}
/**
* Checks if the linked list is empty.
*
* @return true if the linked list is empty, false otherwise
*/
public boolean isEmpty() {
return head == null;
}
}
/**
* A nested static class representing a node in the linked list.
*
* @param <K> the type of key maintained by this node
* @param <V> the type of value maintained by this node
*/
public static class Node<K, V> {
private final K key;
private V value;
private Node<K, V> next;
/**
* Constructs a Node with the specified key and value.
*
* @param key the key associated with this node
* @param value the value associated with this node
*/
public Node(K key, V value) {
this.key = key;
this.value = value;
}
/**
* Gets the key associated with this node.
*
* @return the key associated with this node
*/
public K getKey() {
return key;
}
/**
* Gets the value associated with this node.
*
* @return the value associated with this node
*/
public V getValue() {
return value;
}
public void setValue(V value) { // This method allows updating the value
this.value = value;
}
/**
* Gets the next node in the linked list.
*
* @return the next node in the linked list
*/
public Node<K, V> getNext() {
return next;
}
/**
* Sets the next node in the linked list.
*
* @param next the next node to be linked
*/
public void setNext(Node<K, V> next) {
this.next = next;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/bags/Bag.java | src/main/java/com/thealgorithms/datastructures/bags/Bag.java | package com.thealgorithms.datastructures.bags;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A generic collection that allows adding and iterating over elements but does not support
* element removal. This class implements a simple bag data structure, which can hold duplicate
* elements and provides operations to check for membership and the size of the collection.
*
* <p>Bag is not thread-safe and should not be accessed by multiple threads concurrently.
*
* @param <E> the type of elements in this bag
*/
public class Bag<E> implements Iterable<E> {
private Node<E> firstElement; // Reference to the first element in the bag
private int size; // Count of elements in the bag
// Node class representing each element in the bag
private static final class Node<E> {
private E content;
private Node<E> nextElement;
}
/**
* Constructs an empty bag.
* <p>This initializes the bag with zero elements.
*/
public Bag() {
firstElement = null;
size = 0;
}
/**
* Checks if the bag is empty.
*
* @return {@code true} if the bag contains no elements; {@code false} otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the number of elements in the bag.
*
* @return the number of elements currently in the bag
*/
public int size() {
return size;
}
/**
* Adds an element to the bag.
*
* <p>This method adds the specified element to the bag. Duplicates are allowed, and the
* bag will maintain the order in which elements are added.
*
* @param element the element to add; must not be {@code null}
*/
public void add(E element) {
Node<E> newNode = new Node<>();
newNode.content = element;
newNode.nextElement = firstElement;
firstElement = newNode;
size++;
}
/**
* Checks if the bag contains a specific element.
*
* <p>This method uses the {@code equals} method of the element to determine membership.
*
* @param element the element to check for; must not be {@code null}
* @return {@code true} if the bag contains the specified element; {@code false} otherwise
*/
public boolean contains(E element) {
for (E value : this) {
if (value.equals(element)) {
return true;
}
}
return false;
}
/**
* Returns an iterator over the elements in this bag.
*
* <p>The iterator provides a way to traverse the elements in the order they were added.
*
* @return an iterator that iterates over the elements in the bag
*/
@Override
public Iterator<E> iterator() {
return new ListIterator<>(firstElement);
}
// Private class for iterating over elements
private static class ListIterator<E> implements Iterator<E> {
private Node<E> currentElement;
/**
* Constructs a ListIterator starting from the given first element.
*
* @param firstElement the first element of the bag to iterate over
*/
ListIterator(Node<E> firstElement) {
this.currentElement = firstElement;
}
/**
* Checks if there are more elements to iterate over.
*
* @return {@code true} if there are more elements; {@code false} otherwise
*/
@Override
public boolean hasNext() {
return currentElement != null;
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the bag
* @throws NoSuchElementException if there are no more elements to return
*/
@Override
public E next() {
if (!hasNext()) {
throw new NoSuchElementException("No more elements in the bag.");
}
E element = currentElement.content;
currentElement = currentElement.nextElement;
return element;
}
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java | src/main/java/com/thealgorithms/datastructures/queues/CircularQueue.java | package com.thealgorithms.datastructures.queues;
/**
* The CircularQueue class represents a generic circular queue data structure that uses an array to
* store elements. This queue allows efficient utilization of space by wrapping around the array,
* thus avoiding the need to shift elements during enqueue and dequeue operations.
*
* <p>When the queue reaches its maximum capacity, further enqueues will raise an exception.
* Similarly, attempts to dequeue or peek from an empty queue will also result in an exception.
*
* <p>Reference: <a href="https://en.wikipedia.org/wiki/Circular_buffer">Circular Buffer</a>
*
* <p>Usage Example:
* <pre>
* CircularQueue<Integer> queue = new CircularQueue<>(3);
* queue.enQueue(1);
* queue.enQueue(2);
* queue.enQueue(3);
* queue.deQueue(); // Removes 1
* queue.enQueue(4); // Wraps around and places 4 at the position of removed 1
* </pre>
*
* @param <T> the type of elements in this queue
*/
public class CircularQueue<T> {
private T[] array;
private int topOfQueue;
private int beginningOfQueue;
private final int size;
private int currentSize;
/**
* Constructs a CircularQueue with a specified capacity.
*
* @param size the maximum number of elements this queue can hold
* @throws IllegalArgumentException if the size is less than 1
*/
@SuppressWarnings("unchecked")
public CircularQueue(int size) {
if (size < 1) {
throw new IllegalArgumentException("Size must be greater than 0");
}
this.array = (T[]) new Object[size];
this.topOfQueue = -1;
this.beginningOfQueue = -1;
this.size = size;
this.currentSize = 0;
}
/**
* Checks if the queue is empty.
*
* @return {@code true} if the queue is empty; {@code false} otherwise
*/
public boolean isEmpty() {
return currentSize == 0;
}
/**
* Checks if the queue is full.
*
* @return {@code true} if the queue has reached its maximum capacity; {@code false} otherwise
*/
public boolean isFull() {
return currentSize == size;
}
/**
* Adds a new element to the queue. If the queue is full, an exception is thrown.
*
* @param value the element to be added to the queue
* @throws IllegalStateException if the queue is already full
*/
public void enQueue(T value) {
if (isFull()) {
throw new IllegalStateException("Queue is full");
}
if (isEmpty()) {
beginningOfQueue = 0;
}
topOfQueue = (topOfQueue + 1) % size;
array[topOfQueue] = value;
currentSize++;
}
/**
* Removes and returns the element at the front of the queue.
*
* @return the element at the front of the queue
* @throws IllegalStateException if the queue is empty
*/
public T deQueue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
T removedValue = array[beginningOfQueue];
array[beginningOfQueue] = null; // Optional: Nullify to help garbage collection
beginningOfQueue = (beginningOfQueue + 1) % size;
currentSize--;
if (isEmpty()) {
beginningOfQueue = -1;
topOfQueue = -1;
}
return removedValue;
}
/**
* Returns the element at the front of the queue without removing it.
*
* @return the element at the front of the queue
* @throws IllegalStateException if the queue is empty
*/
public T peek() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
return array[beginningOfQueue];
}
/**
* Deletes the entire queue by resetting all elements and pointers.
*/
public void deleteQueue() {
array = null;
beginningOfQueue = -1;
topOfQueue = -1;
currentSize = 0;
}
/**
* Returns the current number of elements in the queue.
*
* @return the number of elements currently in the queue
*/
public int size() {
return currentSize;
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
TheAlgorithms/Java | https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java | src/main/java/com/thealgorithms/datastructures/queues/LinkedQueue.java | package com.thealgorithms.datastructures.queues;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class LinkedQueue<T> implements Iterable<T> {
/**
* Node class representing each element in the queue.
*/
private static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
this.next = null;
}
}
private Node<T> front; // Front of the queue
private Node<T> rear; // Rear of the queue
private int size; // Size of the queue
/**
* Initializes an empty LinkedQueue.
*/
public LinkedQueue() {
front = null;
rear = null;
size = 0;
}
/**
* Checks if the queue is empty.
*
* @return true if the queue is empty, otherwise false.
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Adds an element to the rear of the queue.
*
* @param data the element to insert.
* @throws IllegalArgumentException if data is null.
*/
public void enqueue(T data) {
if (data == null) {
throw new IllegalArgumentException("Cannot enqueue null data");
}
Node<T> newNode = new Node<>(data);
if (isEmpty()) {
front = newNode;
} else {
rear.next = newNode;
}
rear = newNode;
size++;
}
/**
* Removes and returns the element at the front of the queue.
*
* @return the element at the front of the queue.
* @throws NoSuchElementException if the queue is empty.
*/
public T dequeue() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
T retValue = front.data;
front = front.next;
size--;
if (isEmpty()) {
rear = null;
}
return retValue;
}
/**
* Returns the element at the front of the queue without removing it.
*
* @return the element at the front of the queue.
* @throws NoSuchElementException if the queue is empty.
*/
public T peekFront() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
return front.data;
}
/**
* Returns the element at the rear of the queue without removing it.
*
* @return the element at the rear of the queue.
* @throws NoSuchElementException if the queue is empty.
*/
public T peekRear() {
if (isEmpty()) {
throw new NoSuchElementException("Queue is empty");
}
return rear.data;
}
/**
* Returns the element at the specified position (1-based index).
*
* @param pos the position to peek at (1-based index).
* @return the element at the specified position.
* @throws IndexOutOfBoundsException if the position is out of range.
*/
public T peek(int pos) {
if (pos < 1 || pos > size) {
throw new IndexOutOfBoundsException("Position " + pos + " out of range!");
}
Node<T> node = front;
for (int i = 1; i < pos; i++) {
node = node.next;
}
return node.data;
}
/**
* Returns an iterator over the elements in the queue.
*
* @return an iterator over the elements in the queue.
*/
@Override
public Iterator<T> iterator() {
return new Iterator<>() {
private Node<T> current = front;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T data = current.data;
current = current.next;
return data;
}
};
}
/**
* Returns the size of the queue.
*
* @return the size of the queue.
*/
public int size() {
return size;
}
/**
* Clears all elements from the queue.
*/
public void clear() {
front = null;
rear = null;
size = 0;
}
/**
* Returns a string representation of the queue.
*
* @return a string representation of the queue.
*/
@Override
public String toString() {
if (isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder("[");
Node<T> current = front;
while (current != null) {
sb.append(current.data);
if (current.next != null) {
sb.append(", ");
}
current = current.next;
}
sb.append(']');
return sb.toString();
}
}
| java | MIT | e945f1622490ff3b32e59d31780df27d0dc2ede4 | 2026-01-04T14:45:56.733479Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.