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/datastructures/queues/PriorityQueues.java
src/main/java/com/thealgorithms/datastructures/queues/PriorityQueues.java
package com.thealgorithms.datastructures.queues; /** * This class implements a PriorityQueue. * * <p> * A priority queue adds elements into positions based on their priority. So the * most important elements are placed at the front/on the top. In this example I * give numbers that are bigger, a higher priority. Queues in theory have no * fixed size but when using an array implementation it does. * <p> * Additional contributions made by: PuneetTri(https://github.com/PuneetTri) */ class PriorityQueue { /** * The max size of the queue */ private int maxSize; /** * The array for the queue */ private int[] queueArray; /** * How many items are in the queue */ private int nItems; /** * Default Constructor */ PriorityQueue() { /* If capacity is not defined, default size of 11 would be used * capacity=max+1 because we can't access 0th element of PQ, and to * accommodate (max)th elements we need capacity to be max+1. * Parent is at position k, child at position (k*2,k*2+1), if we * use position 0 in our queue, its child would be at: * (0*2, 0*2+1) -> (0,0). This is why we start at position 1 */ int size = 11; // Default value of 11 maxSize = size + 1; queueArray = new int[maxSize]; nItems = 0; } /** * Parameterized Constructor * * @param size Size of the queue */ PriorityQueue(int size) { maxSize = size + 1; queueArray = new int[maxSize]; nItems = 0; } /** * Helper function for the max-heap implementation of PQ * Function would help demote parent node to their correct * position * * @param pos Position of newly added element at bottom */ private void swim(int pos) { // Check if parent is smaller than child node while (pos > 1 && (queueArray[pos / 2] < queueArray[pos])) { // In such case swap value of child with parent int temp = queueArray[pos]; queueArray[pos] = queueArray[pos / 2]; queueArray[pos / 2] = temp; pos = pos / 2; // Jump to position of parent node } // Promotion of child node will go on until it becomes smaller than the parent } /** * Helper function for the max-heap implementation of PQ * Function would help demote parent node to their correct * position * * @param pos Position of element at top */ private void sink(int pos) { // Check if node's position is that of parent node while (2 * pos <= nItems) { int current = 2 * pos; // Jump to the positon of child node // Compare both the children for the greater one if (current < nItems && queueArray[current] < queueArray[current + 1]) { current++; } // If the parent node is greater, sink operation is complete. Break the loop if (queueArray[pos] >= queueArray[current]) { break; } // If not exchange the value of parent with child int temp = queueArray[pos]; queueArray[pos] = queueArray[current]; queueArray[current] = temp; pos = current; // Exchange parent position to child position in the array } } /** * Inserts an element in it's appropriate place * * @param value Value to be inserted */ public void insert(int value) { // Print overflow message if the capacity is full if (isFull()) { throw new RuntimeException("Queue is full"); } else { queueArray[++nItems] = value; swim(nItems); // Swim up the element to its correct position } } /** * Dequeue the element with the max priority from PQ * * @return The element removed */ public int remove() { if (isEmpty()) { throw new RuntimeException("Queue is Empty"); } else { int max = queueArray[1]; // By definition of our max-heap, value at queueArray[1] pos is // the greatest // Swap max and last element int temp = queueArray[1]; queueArray[1] = queueArray[nItems]; queueArray[nItems] = temp; queueArray[nItems--] = 0; // Nullify the last element from the priority queue sink(1); // Sink the element in order return max; } } /** * Checks what's at the front of the queue * * @return element at the front of the queue */ public int peek() { return queueArray[1]; } /** * Returns true if the queue is empty * * @return true if the queue is empty */ public boolean isEmpty() { return (nItems == 0); } /** * Returns true if the queue is full * * @return true if the queue is full */ public boolean isFull() { return (nItems == maxSize - 1); } /** * Returns the number of elements in the queue * * @return number of elements in the queue */ public int getSize() { return nItems; } }
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/GenericArrayListQueue.java
src/main/java/com/thealgorithms/datastructures/queues/GenericArrayListQueue.java
package com.thealgorithms.datastructures.queues; import java.util.ArrayList; import java.util.List; /** * This class implements a GenericArrayListQueue, a queue data structure that * holds elements of any type specified at runtime, allowing flexibility in the type * of elements it stores. * * <p>The GenericArrayListQueue operates on a First-In-First-Out (FIFO) basis, where * elements added first are the first to be removed. New elements are added to the back * (or rear) of the queue, while removal of elements occurs from the front. * * @param <T> The type of elements held in this queue. */ public class GenericArrayListQueue<T> { /** * A list that stores the queue's elements in insertion order. */ private final List<T> elementList = new ArrayList<>(); /** * Checks if the queue is empty. * * @return {@code true} if the queue has no elements; {@code false} otherwise. */ public boolean isEmpty() { return elementList.isEmpty(); } /** * Retrieves, but does not remove, the element at the front of the queue. * * @return The element at the front of the queue, or {@code null} if the queue is empty. */ public T peek() { return isEmpty() ? null : elementList.getFirst(); } /** * Inserts an element at the back of the queue. * * @param element The element to be added to the queue. * @return {@code true} if the element was successfully added. */ public boolean add(T element) { return elementList.add(element); } /** * Retrieves and removes the element at the front of the queue. * * @return The element removed from the front of the queue, or {@code null} if the queue is empty. */ public T poll() { return isEmpty() ? null : elementList.removeFirst(); } }
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/TokenBucket.java
src/main/java/com/thealgorithms/datastructures/queues/TokenBucket.java
package com.thealgorithms.datastructures.queues; import java.util.concurrent.TimeUnit; /** * TokenBucket implements a token bucket rate limiter algorithm. * This class is used to control the rate of requests in a distributed system. * It allows a certain number of requests (tokens) to be processed in a time frame, * based on the defined refill rate. * * Applications: Computer networks, API rate limiting, distributed systems, etc. * * @author Hardvan */ public final class TokenBucket { private final int maxTokens; private final int refillRate; // tokens per second private int tokens; private long lastRefill; // Timestamp in nanoseconds /** * Constructs a TokenBucket instance. * * @param maxTokens Maximum number of tokens the bucket can hold. * @param refillRate The rate at which tokens are refilled (tokens per second). */ public TokenBucket(int maxTokens, int refillRate) { this.maxTokens = maxTokens; this.refillRate = refillRate; this.tokens = maxTokens; this.lastRefill = System.nanoTime(); } /** * Attempts to allow a request based on the available tokens. * If a token is available, it decrements the token count and allows the request. * Otherwise, the request is denied. * * @return true if the request is allowed, false if the request is denied. */ public synchronized boolean allowRequest() { refillTokens(); if (tokens > 0) { tokens--; return true; } return false; } /** * Refills the tokens based on the time elapsed since the last refill. * The number of tokens to be added is calculated based on the elapsed time * and the refill rate, ensuring the total does not exceed maxTokens. */ private void refillTokens() { long now = System.nanoTime(); long tokensToAdd = (now - lastRefill) / TimeUnit.SECONDS.toNanos(1) * refillRate; tokens = Math.min(maxTokens, tokens + (int) tokensToAdd); lastRefill = now; } }
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/Deque.java
src/main/java/com/thealgorithms/datastructures/queues/Deque.java
package com.thealgorithms.datastructures.queues; import java.util.NoSuchElementException; /** * A [deque](https://en.wikipedia.org/wiki/Double-ended_queue) is short for a * double ended queue pronounced "deck" and sometimes referred to as a head-tail * linked list. A deque is a data structure based on a doubly linked list, but * only supports adding and removal of nodes from the beginning and the end of * the list. * * @author [Ian Cowan](https://github.com/iccowan) */ public class Deque<T> { /** * Node for the deque */ private static class DequeNode<S> { S val; DequeNode<S> next = null; DequeNode<S> prev = null; DequeNode(S val) { this.val = val; } } private DequeNode<T> head = null; private DequeNode<T> tail = null; private int size = 0; /** * Adds the specified value to the head of the deque * * @param val Value to add to the deque */ public void addFirst(T val) { DequeNode<T> newNode = new DequeNode<>(val); if (isEmpty()) { head = newNode; tail = newNode; } else { newNode.next = head; head.prev = newNode; head = newNode; } size++; } /** * Adds the specified value to the tail of the deque * * @param val Value to add to the deque */ public void addLast(T val) { DequeNode<T> newNode = new DequeNode<>(val); if (tail == null) { head = newNode; tail = newNode; } else { newNode.prev = tail; tail.next = newNode; tail = newNode; } size++; } /** * Removes and returns the first (head) value in the deque * * @return the value of the head of the deque * @throws NoSuchElementException if the deque is empty */ public T pollFirst() { if (head == null) { throw new NoSuchElementException("Deque is empty"); } T oldHeadVal = head.val; if (head == tail) { head = null; tail = null; } else { head = head.next; head.prev = null; } size--; return oldHeadVal; } /** * Removes and returns the last (tail) value in the deque * * @return the value of the tail of the deque * @throws NoSuchElementException if the deque is empty */ public T pollLast() { if (tail == null) { throw new NoSuchElementException("Deque is empty"); } T oldTailVal = tail.val; if (head == tail) { head = null; tail = null; } else { tail = tail.prev; tail.next = null; } size--; return oldTailVal; } /** * Returns the first (head) value of the deque WITHOUT removing * * @return the value of the head of the deque, or null if empty */ public T peekFirst() { return head != null ? head.val : null; } /** * Returns the last (tail) value of the deque WITHOUT removing * * @return the value of the tail of the deque, or null if empty */ public T peekLast() { return tail != null ? tail.val : null; } /** * Returns the size of the deque * * @return the size of the deque */ public int size() { return size; } /** * Returns whether or not the deque is empty * * @return whether or not the deque is empty */ public boolean isEmpty() { return size == 0; } /** * Returns a stringified deque in a pretty form: * * <p> * Head -> 1 <-> 2 <-> 3 <- Tail * * @return the stringified deque */ @Override public String toString() { StringBuilder dequeString = new StringBuilder("Head -> "); DequeNode<T> currNode = head; while (currNode != null) { dequeString.append(currNode.val); if (currNode.next != null) { dequeString.append(" <-> "); } currNode = currNode.next; } dequeString.append(" <- Tail"); return dequeString.toString(); } public static void main(String[] args) { Deque<Integer> myDeque = new Deque<>(); for (int i = 0; i < 42; i++) { if (i / 42.0 < 0.5) { myDeque.addFirst(i); } else { myDeque.addLast(i); } } System.out.println(myDeque); System.out.println("Size: " + myDeque.size()); System.out.println(); myDeque.pollFirst(); myDeque.pollFirst(); myDeque.pollLast(); System.out.println(myDeque); System.out.println("Size: " + myDeque.size()); System.out.println(); int dequeSize = myDeque.size(); for (int i = 0; i < dequeSize; i++) { int removing = -1; if (i / 39.0 < 0.5) { removing = myDeque.pollFirst(); } else { removing = myDeque.pollLast(); } System.out.println("Removing: " + removing); } System.out.println(myDeque); System.out.println(myDeque.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/queues/SlidingWindowMaximum.java
src/main/java/com/thealgorithms/datastructures/queues/SlidingWindowMaximum.java
package com.thealgorithms.datastructures.queues; import java.util.Deque; import java.util.LinkedList; /** * The {@code SlidingWindowMaximum} class provides a method to efficiently compute * the maximum element within every sliding window of size {@code k} in a given array. * * <p>The algorithm uses a deque to maintain the indices of useful elements within * the current sliding window. The time complexity of this approach is O(n) since * each element is processed at most twice. * * @author Hardvan */ public final class SlidingWindowMaximum { private SlidingWindowMaximum() { } /** * Returns an array of the maximum values for each sliding window of size {@code k}. * <p>If {@code nums} has fewer elements than {@code k}, the result will be an empty array. * <p>Example: * <pre> * Input: nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3 * Output: [3, 3, 5, 5, 6, 7] * </pre> * * @param nums the input array of integers * @param k the size of the sliding window * @return an array containing the maximum element for each sliding window */ public static int[] maxSlidingWindow(int[] nums, int k) { int n = nums.length; if (n < k || k == 0) { return new int[0]; } int[] result = new int[n - k + 1]; Deque<Integer> deque = new LinkedList<>(); for (int i = 0; i < n; i++) { // Remove elements from the front of the deque if they are out of the current window if (!deque.isEmpty() && deque.peekFirst() < i - k + 1) { deque.pollFirst(); } // Remove elements from the back if they are smaller than the current element while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) { deque.pollLast(); } // Add the current element's index to the deque deque.offerLast(i); // Store the maximum element for the current window (starting from the k-1th element) if (i >= k - 1) { result[i - k + 1] = nums[deque.peekFirst()]; } } 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/queues/QueueByTwoStacks.java
src/main/java/com/thealgorithms/datastructures/queues/QueueByTwoStacks.java
package com.thealgorithms.datastructures.queues; import java.util.NoSuchElementException; import java.util.Stack; /** * A queue implementation using two stacks. This class provides methods to * enqueue (add) elements to the end of the queue and dequeue (remove) * elements from the front, while utilizing two internal stacks to manage * the order of elements. * * @param <T> The type of elements held in this queue. */ @SuppressWarnings("unchecked") public class QueueByTwoStacks<T> { private final Stack<T> enqueueStk; private final Stack<T> dequeueStk; /** * Constructor that initializes two empty stacks for the queue. * The `enqueueStk` is used to push elements when enqueuing, and * the `dequeueStk` is used to pop elements when dequeuing. */ public QueueByTwoStacks() { enqueueStk = new Stack<>(); dequeueStk = new Stack<>(); } /** * Adds an element to the end of the queue. This method pushes the element * onto the `enqueueStk`. * * @param item The element to be added to the queue. */ public void put(T item) { enqueueStk.push(item); } /** * Removes and returns the element at the front of the queue. * If `dequeueStk` is empty, it transfers all elements from * `enqueueStk` to `dequeueStk` to maintain the correct FIFO * (First-In-First-Out) order before popping. * * @return The element at the front of the queue. * @throws NoSuchElementException If the queue is empty. */ public T get() { if (dequeueStk.isEmpty()) { while (!enqueueStk.isEmpty()) { dequeueStk.push(enqueueStk.pop()); } } if (dequeueStk.isEmpty()) { throw new NoSuchElementException("Queue is empty"); } return dequeueStk.pop(); } /** * Returns the total number of elements currently in the queue. * This is the sum of the sizes of both stacks. * * @return The number of elements in the queue. */ public int size() { return enqueueStk.size() + dequeueStk.size(); } /** * Returns a string representation of the queue, showing the elements * in the correct order (from front to back). * The `dequeueStk` is first cloned, and then all elements from the * `enqueueStk` are added to the cloned stack in reverse order to * represent the queue accurately. * * @return A string representation of the queue. */ @Override public String toString() { Stack<T> tempStack = (Stack<T>) dequeueStk.clone(); while (!enqueueStk.isEmpty()) { tempStack.push(enqueueStk.pop()); } return "Queue(" + tempStack + ")"; } }
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/Queue.java
src/main/java/com/thealgorithms/datastructures/queues/Queue.java
package com.thealgorithms.datastructures.queues; /** * This class implements a Queue data structure using an array. * A queue is a first-in-first-out (FIFO) data structure where elements are * added to the rear and removed from the front. * * Note: This implementation is not thread-safe. */ public final class Queue<T> { private static final int DEFAULT_CAPACITY = 10; private final int maxSize; private final Object[] queueArray; private int front; private int rear; private int nItems; /** * Initializes a queue with a default capacity. */ public Queue() { this(DEFAULT_CAPACITY); } /** * Constructor to initialize a queue with a specified capacity. * * @param capacity The initial size of the queue. * @throws IllegalArgumentException if the capacity is less than or equal to zero. */ public Queue(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Queue capacity must be greater than 0"); } this.maxSize = capacity; this.queueArray = new Object[capacity]; this.front = 0; this.rear = -1; this.nItems = 0; } /** * Inserts an element at the rear of the queue. * * @param element Element to be added. * @return True if the element was added successfully, false if the queue is full. */ public boolean insert(T element) { if (isFull()) { return false; } rear = (rear + 1) % maxSize; queueArray[rear] = element; nItems++; return true; } /** * Removes and returns the element from the front of the queue. * * @return The element removed from the front of the queue. * @throws IllegalStateException if the queue is empty. */ @SuppressWarnings("unchecked") public T remove() { if (isEmpty()) { throw new IllegalStateException("Queue is empty, cannot remove element"); } T removedElement = (T) queueArray[front]; queueArray[front] = null; // Optional: Clear the reference for garbage collection front = (front + 1) % maxSize; nItems--; return removedElement; } /** * Checks the element at the front of the queue without removing it. * * @return Element at the front of the queue. * @throws IllegalStateException if the queue is empty. */ @SuppressWarnings("unchecked") public T peekFront() { if (isEmpty()) { throw new IllegalStateException("Queue is empty, cannot peek front"); } return (T) queueArray[front]; } /** * Checks the element at the rear of the queue without removing it. * * @return Element at the rear of the queue. * @throws IllegalStateException if the queue is empty. */ @SuppressWarnings("unchecked") public T peekRear() { if (isEmpty()) { throw new IllegalStateException("Queue is empty, cannot peek rear"); } return (T) queueArray[rear]; } /** * Returns true if the queue is empty. * * @return True if the queue is empty. */ public boolean isEmpty() { return nItems == 0; } /** * Returns true if the queue is full. * * @return True if the queue is full. */ public boolean isFull() { return nItems == maxSize; } /** * Returns the number of elements currently in the queue. * * @return Number of elements in the queue. */ public int getSize() { return nItems; } /** * Returns a string representation of the queue. * * @return String representation of the queue. */ @Override public String toString() { if (isEmpty()) { return "[]"; } StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < nItems; i++) { int index = (front + i) % maxSize; sb.append(queueArray[index]).append(", "); } sb.setLength(sb.length() - 2); // Remove the last comma and space 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/crdt/TwoPSet.java
src/main/java/com/thealgorithms/datastructures/crdt/TwoPSet.java
package com.thealgorithms.datastructures.crdt; import java.util.HashSet; import java.util.Set; /** * TwoPhaseSet (2P-Set) is a state-based CRDT (Conflict-free Replicated Data Type) designed for managing sets * with support for both addition and removal operations in a distributed and concurrent environment. * It combines two G-Sets (grow-only sets) - one set for additions and another set (tombstone set) for removals. * Once an element is removed and placed in the tombstone set, it cannot be re-added, adhering to "remove-wins" semantics. * This implementation supports querying the presence of elements, adding elements, removing elements, * comparing with other 2P-Sets, and merging two 2P-Sets while preserving the remove-wins semantics. * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) * * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) */ public class TwoPSet<T> { private final Set<T> setA; private final Set<T> setR; /** * Constructs an empty Two-Phase Set. */ public TwoPSet() { this.setA = new HashSet<>(); this.setR = new HashSet<>(); } /** * Checks if an element is in the set and has not been removed. * * @param element The element to be checked. * @return True if the element is in the set and has not been removed, otherwise false. */ public boolean lookup(T element) { return setA.contains(element) && !setR.contains(element); } /** * Adds an element to the set. * * @param element The element to be added. */ public void add(T element) { setA.add(element); } /** * Removes an element from the set. The element will be placed in the tombstone set. * * @param element The element to be removed. */ public void remove(T element) { if (lookup(element)) { setR.add(element); } } /** * Compares the current 2P-Set with another 2P-Set. * * @param otherSet The other 2P-Set to compare with. * @return True if both SetA and SetR are subset, otherwise false. */ public boolean compare(TwoPSet<T> otherSet) { return otherSet.setA.containsAll(setA) && otherSet.setR.containsAll(setR); } /** * Merges the current 2P-Set with another 2P-Set. * * @param otherSet The other 2P-Set to merge with. * @return A new 2P-Set containing the merged elements. */ public TwoPSet<T> merge(TwoPSet<T> otherSet) { TwoPSet<T> mergedSet = new TwoPSet<>(); mergedSet.setA.addAll(this.setA); mergedSet.setA.addAll(otherSet.setA); mergedSet.setR.addAll(this.setR); mergedSet.setR.addAll(otherSet.setR); return mergedSet; } }
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/crdt/GSet.java
src/main/java/com/thealgorithms/datastructures/crdt/GSet.java
package com.thealgorithms.datastructures.crdt; import java.util.HashSet; import java.util.Set; /** * GSet (Grow-only Set) is a state-based CRDT (Conflict-free Replicated Data Type) * that allows only the addition of elements and ensures that once an element is added, * it cannot be removed. The merge operation of two G-Sets is their union. * This implementation supports adding elements, looking up elements, comparing with other G-Sets, * and merging with another G-Set to create a new G-Set containing all unique elements from both sets. * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) * * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) */ public class GSet<T> { private final Set<T> elements; /** * Constructs an empty G-Set. */ public GSet() { this.elements = new HashSet<>(); } /** * Adds an element to the G-Set. * * @param e the element to be added */ public void addElement(T e) { elements.add(e); } /** * Checks if the given element is present in the G-Set. * * @param e the element to be checked * @return true if the element is present, false otherwise */ public boolean lookup(T e) { return elements.contains(e); } /** * Compares the G-Set with another G-Set to check if it is a subset. * * @param other the other G-Set to compare with * @return true if the current G-Set is a subset of the other, false otherwise */ public boolean compare(GSet<T> other) { return other.elements.containsAll(elements); } /** * Merges the current G-Set with another G-Set, creating a new G-Set * containing all unique elements from both sets. * * @param other the G-Set to merge with */ public void merge(GSet<T> other) { elements.addAll(other.elements); } }
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/crdt/LWWElementSet.java
src/main/java/com/thealgorithms/datastructures/crdt/LWWElementSet.java
package com.thealgorithms.datastructures.crdt; import java.time.Instant; import java.util.HashMap; import java.util.Map; /** * Last-Write-Wins Element Set (LWWElementSet) is a state-based CRDT (Conflict-free Replicated Data * Type) designed for managing sets in a distributed and concurrent environment. It supports the * addition and removal of elements, using timestamps to determine the order of operations. The set * is split into two subsets: the add set for elements to be added and the remove set for elements * to be removed. The LWWElementSet ensures that the most recent operation (based on the timestamp) * wins in the case of concurrent operations. * * @param <T> The type of the elements in the LWWElementSet. * @author <a href="https://github.com/itakurah">itakurah (GitHub)</a>, <a * href="https://www.linkedin.com/in/niklashoefflin/">Niklas Hoefflin (LinkedIn)</a> * @see <a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type">Conflict free * replicated data type (Wikipedia)</a> * @see <a href="https://inria.hal.science/inria-00555588v1/document">A comprehensive study of * Convergent and Commutative Replicated Data Types</a> */ class LWWElementSet<T> { final Map<T, Element<T>> addSet; final Map<T, Element<T>> removeSet; /** * Constructs an empty LWWElementSet. This constructor initializes the addSet and removeSet as * empty HashMaps. The addSet stores elements that are added, and the removeSet stores elements * that are removed. */ LWWElementSet() { this.addSet = new HashMap<>(); this.removeSet = new HashMap<>(); } /** * Adds an element to the addSet with the current timestamp. This method stores the element in the * addSet, ensuring that the element is added to the set with an associated timestamp that * represents the time of the addition. * * @param key The key of the element to be added. */ public void add(T key) { addSet.put(key, new Element<>(key, Instant.now())); } /** * Removes an element by adding it to the removeSet with the current timestamp. This method adds * the element to the removeSet, marking it as removed with the current timestamp. * * @param key The key of the element to be removed. */ public void remove(T key) { removeSet.put(key, new Element<>(key, Instant.now())); } /** * Checks if an element is in the LWWElementSet. An element is considered present if it exists in * the addSet and either does not exist in the removeSet, or its add timestamp is later than any * corresponding remove timestamp. * * @param key The key of the element to be checked. * @return {@code true} if the element is present in the set (i.e., its add timestamp is later * than its remove timestamp, or it is not in the remove set), {@code false} otherwise (i.e., * the element has been removed or its remove timestamp is later than its add timestamp). */ public boolean lookup(T key) { Element<T> inAddSet = addSet.get(key); Element<T> inRemoveSet = removeSet.get(key); return inAddSet != null && (inRemoveSet == null || inAddSet.timestamp.isAfter(inRemoveSet.timestamp)); } /** * Merges another LWWElementSet into this set. This method takes the union of both the add-sets * and remove-sets from the two sets, resolving conflicts by keeping the element with the latest * timestamp. If an element appears in both the add-set and remove-set of both sets, the one with * the later timestamp will be retained. * * @param other The LWWElementSet to merge with the current set. */ public void merge(LWWElementSet<T> other) { for (Map.Entry<T, Element<T>> entry : other.addSet.entrySet()) { addSet.merge(entry.getKey(), entry.getValue(), this::resolveConflict); } for (Map.Entry<T, Element<T>> entry : other.removeSet.entrySet()) { removeSet.merge(entry.getKey(), entry.getValue(), this::resolveConflict); } } /** * Resolves conflicts between two elements by selecting the one with the later timestamp. This * method is used when merging two LWWElementSets to ensure that the most recent operation (based * on timestamps) is kept. * * @param e1 The first element. * @param e2 The second element. * @return The element with the later timestamp. */ private Element<T> resolveConflict(Element<T> e1, Element<T> e2) { return e1.timestamp.isAfter(e2.timestamp) ? e1 : e2; } } /** * Represents an element in the LWWElementSet, consisting of a key and a timestamp. This class is * used to store the elements in both the add and remove sets with their respective timestamps. * * @param <T> The type of the key associated with the element. */ class Element<T> { T key; Instant timestamp; /** * Constructs a new Element with the specified key and timestamp. * * @param key The key of the element. * @param timestamp The timestamp associated with the element. */ Element(T key, Instant timestamp) { this.key = key; this.timestamp = timestamp; } }
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/crdt/PNCounter.java
src/main/java/com/thealgorithms/datastructures/crdt/PNCounter.java
package com.thealgorithms.datastructures.crdt; import java.util.HashMap; import java.util.Map; /** * PN-Counter (Positive-Negative Counter) is a state-based CRDT (Conflict-free Replicated Data Type) * designed for tracking counts with both increments and decrements in a distributed and concurrent environment. * It combines two G-Counters, one for increments (P) and one for decrements (N). * The total count is obtained by subtracting the value of the decrement counter from the increment counter. * This implementation supports incrementing, decrementing, querying the total count, * comparing with other PN-Counters, and merging with another PN-Counter * to compute the element-wise maximum for both increment and decrement counters. * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) * * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) */ class PNCounter { private final Map<Integer, Integer> pCounter; private final Map<Integer, Integer> nCounter; private final int myId; private final int n; /** * Constructs a PN-Counter for a cluster of n nodes. * * @param myId The identifier of the current node. * @param n The number of nodes in the cluster. */ PNCounter(int myId, int n) { this.myId = myId; this.n = n; this.pCounter = new HashMap<>(); this.nCounter = new HashMap<>(); for (int i = 0; i < n; i++) { pCounter.put(i, 0); nCounter.put(i, 0); } } /** * Increments the increment counter for the current node. */ public void increment() { pCounter.put(myId, pCounter.get(myId) + 1); } /** * Increments the decrement counter for the current node. */ public void decrement() { nCounter.put(myId, nCounter.get(myId) + 1); } /** * Gets the total value of the counter by subtracting the decrement counter from the increment counter. * * @return The total value of the counter. */ public int value() { int sumP = pCounter.values().stream().mapToInt(Integer::intValue).sum(); int sumN = nCounter.values().stream().mapToInt(Integer::intValue).sum(); return sumP - sumN; } /** * Compares the state of this PN-Counter with another PN-Counter. * * @param other The other PN-Counter to compare with. * @return True if the state of this PN-Counter is less than or equal to the state of the other PN-Counter. */ public boolean compare(PNCounter other) { if (this.n != other.n) { throw new IllegalArgumentException("Cannot compare PN-Counters with different number of nodes"); } for (int i = 0; i < n; i++) { if (this.pCounter.get(i) > other.pCounter.get(i) && this.nCounter.get(i) > other.nCounter.get(i)) { return false; } } return true; } /** * Merges the state of this PN-Counter with another PN-Counter. * * @param other The other PN-Counter to merge with. */ public void merge(PNCounter other) { if (this.n != other.n) { throw new IllegalArgumentException("Cannot merge PN-Counters with different number of nodes"); } for (int i = 0; i < n; i++) { this.pCounter.put(i, Math.max(this.pCounter.get(i), other.pCounter.get(i))); this.nCounter.put(i, Math.max(this.nCounter.get(i), other.nCounter.get(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/crdt/ORSet.java
src/main/java/com/thealgorithms/datastructures/crdt/ORSet.java
package com.thealgorithms.datastructures.crdt; import java.util.HashSet; import java.util.Set; import java.util.UUID; /** * ORSet (Observed-Removed Set) is a state-based CRDT (Conflict-free Replicated Data Type) * that supports both addition and removal of elements. This particular implementation follows * the Add-Wins strategy, meaning that in case of conflicting add and remove operations, * the add operation takes precedence. The merge operation of two OR-Sets ensures that * elements added at any replica are eventually observed at all replicas. Removed elements, * once observed, are never reintroduced. * This OR-Set implementation provides methods for adding elements, removing elements, * checking for element existence, retrieving the set of elements, comparing with other OR-Sets, * and merging with another OR-Set to create a new OR-Set containing all unique elements * from both sets. * * @author itakurah (Niklas Hoefflin) (https://github.com/itakurah) * @see <a href="https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type">Conflict-free_replicated_data_type</a> * @see <a href="https://github.com/itakurah">itakurah (Niklas Hoefflin)</a> */ public class ORSet<T> { private final Set<Pair<T>> elements; private final Set<Pair<T>> tombstones; /** * Constructs an empty OR-Set. */ public ORSet() { this.elements = new HashSet<>(); this.tombstones = new HashSet<>(); } /** * Checks if the set contains the specified element. * * @param element the element to check for * @return true if the set contains the element, false otherwise */ public boolean contains(T element) { return elements.stream().anyMatch(pair -> pair.getElement().equals(element)); } /** * Retrieves the elements in the set. * * @return a set containing the elements */ public Set<T> elements() { Set<T> result = new HashSet<>(); elements.forEach(pair -> result.add(pair.getElement())); return result; } /** * Adds the specified element to the set. * * @param element the element to add */ public void add(T element) { String n = prepare(); effect(element, n); } /** * Removes the specified element from the set. * * @param element the element to remove */ public void remove(T element) { Set<Pair<T>> pairsToRemove = prepare(element); effect(pairsToRemove); } /** * Collect all pairs with the specified element. * * @param element the element to collect pairs for * @return a set of pairs with the specified element to be removed */ private Set<Pair<T>> prepare(T element) { Set<Pair<T>> pairsToRemove = new HashSet<>(); for (Pair<T> pair : elements) { if (pair.getElement().equals(element)) { pairsToRemove.add(pair); } } return pairsToRemove; } /** * Generates a unique tag for the element. * * @return the unique tag */ private String prepare() { return generateUniqueTag(); } /** * Adds the element with the specified unique tag to the set. * * @param element the element to add * @param n the unique tag associated with the element */ private void effect(T element, String n) { Pair<T> pair = new Pair<>(element, n); elements.add(pair); elements.removeAll(tombstones); } /** * Removes the specified pairs from the set. * * @param pairsToRemove the pairs to remove */ private void effect(Set<Pair<T>> pairsToRemove) { elements.removeAll(pairsToRemove); tombstones.addAll(pairsToRemove); } /** * Generates a unique tag. * * @return the unique tag */ private String generateUniqueTag() { return UUID.randomUUID().toString(); } /** * Compares this Add-Wins OR-Set with another OR-Set to check if elements and tombstones are a subset. * * @param other the other OR-Set to compare * @return true if the sets are subset, false otherwise */ public boolean compare(ORSet<T> other) { Set<Pair<T>> union = new HashSet<>(elements); union.addAll(tombstones); Set<Pair<T>> otherUnion = new HashSet<>(other.elements); otherUnion.addAll(other.tombstones); return otherUnion.containsAll(union) && other.tombstones.containsAll(tombstones); } /** * Merges this Add-Wins OR-Set with another OR-Set. * * @param other the other OR-Set to merge */ public void merge(ORSet<T> other) { elements.removeAll(other.tombstones); other.elements.removeAll(tombstones); elements.addAll(other.elements); tombstones.addAll(other.tombstones); } /** * Represents a pair containing an element and a unique tag. * * @param <T> the type of the element in the pair */ public static class Pair<T> { private final T element; private final String uniqueTag; /** * Constructs a pair with the specified element and unique tag. * * @param element the element in the pair * @param uniqueTag the unique tag associated with the element */ public Pair(T element, String uniqueTag) { this.element = element; this.uniqueTag = uniqueTag; } /** * Gets the element from the pair. * * @return the element */ public T getElement() { 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/crdt/GCounter.java
src/main/java/com/thealgorithms/datastructures/crdt/GCounter.java
package com.thealgorithms.datastructures.crdt; import java.util.HashMap; import java.util.Map; /** * G-Counter (Grow-only Counter) is a state-based CRDT (Conflict-free Replicated Data Type) * designed for tracking counts in a distributed and concurrent environment. * Each process maintains its own counter, allowing only increments. The total count * is obtained by summing individual process counts. * This implementation supports incrementing, querying the total count, * comparing with other G-Counters, and merging with another G-Counter * to compute the element-wise maximum. * (https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type) * * @author itakurah (https://github.com/itakurah) */ class GCounter { private final Map<Integer, Integer> counterMap; private final int myId; private final int n; /** * Constructs a G-Counter for a cluster of n nodes. * * @param n The number of nodes in the cluster. */ GCounter(int myId, int n) { this.myId = myId; this.n = n; this.counterMap = new HashMap<>(); for (int i = 0; i < n; i++) { counterMap.put(i, 0); } } /** * Increments the counter for the current node. */ public void increment() { counterMap.put(myId, counterMap.get(myId) + 1); } /** * Gets the total value of the counter by summing up values from all nodes. * * @return The total value of the counter. */ public int value() { int sum = 0; for (int v : counterMap.values()) { sum += v; } return sum; } /** * Compares the state of this G-Counter with another G-Counter. * * @param other The other G-Counter to compare with. * @return True if the state of this G-Counter is less than or equal to the state of the other G-Counter. */ public boolean compare(GCounter other) { for (int i = 0; i < n; i++) { if (this.counterMap.get(i) > other.counterMap.get(i)) { return false; } } return true; } /** * Merges the state of this G-Counter with another G-Counter. * * @param other The other G-Counter to merge with. */ public void merge(GCounter other) { for (int i = 0; i < n; i++) { this.counterMap.put(i, Math.max(this.counterMap.get(i), other.counterMap.get(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/buffers/CircularBuffer.java
src/main/java/com/thealgorithms/datastructures/buffers/CircularBuffer.java
package com.thealgorithms.datastructures.buffers; import java.util.concurrent.atomic.AtomicInteger; /** * The {@code CircularBuffer} class implements a generic circular (or ring) buffer. * A circular buffer is a fixed-size data structure that operates in a FIFO (First In, First Out) manner. * The buffer allows you to overwrite old data when the buffer is full and efficiently use limited memory. * When the buffer is full, adding a new item will overwrite the oldest data. * * @param <Item> The type of elements stored in the circular buffer. */ @SuppressWarnings("unchecked") public class CircularBuffer<Item> { private final Item[] buffer; private final CircularPointer putPointer; private final CircularPointer getPointer; private final AtomicInteger size = new AtomicInteger(0); /** * Constructor to initialize the circular buffer with a specified size. * * @param size The size of the circular buffer. * @throws IllegalArgumentException if the size is zero or negative. */ public CircularBuffer(int size) { if (size <= 0) { throw new IllegalArgumentException("Buffer size must be positive"); } // noinspection unchecked this.buffer = (Item[]) new Object[size]; this.putPointer = new CircularPointer(0, size); this.getPointer = new CircularPointer(0, size); } /** * Checks if the circular buffer is empty. * This method is based on the current size of the buffer. * * @return {@code true} if the buffer is empty, {@code false} otherwise. */ public boolean isEmpty() { return size.get() == 0; } /** * Checks if the circular buffer is full. * The buffer is considered full when its size equals its capacity. * * @return {@code true} if the buffer is full, {@code false} otherwise. */ public boolean isFull() { return size.get() == buffer.length; } /** * Retrieves and removes the item at the front of the buffer (FIFO). * This operation will move the {@code getPointer} forward. * * @return The item at the front of the buffer, or {@code null} if the buffer is empty. */ public Item get() { if (isEmpty()) { return null; } Item item = buffer[getPointer.getAndIncrement()]; size.decrementAndGet(); return item; } /** * Adds an item to the end of the buffer (FIFO). * If the buffer is full, this operation will overwrite the oldest data. * * @param item The item to be added. * @throws IllegalArgumentException if the item is null. * @return {@code true} if the item was successfully added, {@code false} if the buffer was full and the item overwrote existing data. */ public boolean put(Item item) { if (item == null) { throw new IllegalArgumentException("Null items are not allowed"); } boolean wasEmpty = isEmpty(); if (isFull()) { getPointer.getAndIncrement(); // Move get pointer to discard oldest item } else { size.incrementAndGet(); } buffer[putPointer.getAndIncrement()] = item; return wasEmpty; } /** * The {@code CircularPointer} class is a helper class used to track the current index (pointer) * in the circular buffer. * The max value represents the capacity of the buffer. * The `CircularPointer` class ensures that the pointer automatically wraps around to 0 * when it reaches the maximum index. * This is achieved in the `getAndIncrement` method, where the pointer * is incremented and then taken modulo the maximum value (`max`). * This operation ensures that the pointer always stays within the bounds of the buffer. */ private static class CircularPointer { private int pointer; private final int max; /** * Constructor to initialize the circular pointer. * * @param pointer The initial position of the pointer. * @param max The maximum size (capacity) of the circular buffer. */ CircularPointer(int pointer, int max) { this.pointer = pointer; this.max = max; } /** * Increments the pointer by 1 and wraps it around to 0 if it reaches the maximum value. * This ensures the pointer always stays within the buffer's bounds. * * @return The current pointer value before incrementing. */ public int getAndIncrement() { int tmp = pointer; pointer = (pointer + 1) % max; return tmp; } } }
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/graphs/AStar.java
src/main/java/com/thealgorithms/datastructures/graphs/AStar.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; /** * AStar class implements the A* pathfinding algorithm to find the shortest path in a graph. * The graph is represented using an adjacency list, and the algorithm uses a heuristic to estimate * the cost to reach the destination node. * Time Complexity = O(E), where E is equal to the number of edges */ public final class AStar { private AStar() { } /** * Represents a graph using an adjacency list. */ static class Graph { private ArrayList<ArrayList<Edge>> graph; Graph(int size) { this.graph = new ArrayList<>(); for (int i = 0; i < size; i++) { this.graph.add(new ArrayList<>()); } } private ArrayList<Edge> getNeighbours(int from) { return this.graph.get(from); } // Add a bidirectional edge to the graph private void addEdge(Edge edge) { this.graph.get(edge.getFrom()).add(new Edge(edge.getFrom(), edge.getTo(), edge.getWeight())); this.graph.get(edge.getTo()).add(new Edge(edge.getTo(), edge.getFrom(), edge.getWeight())); } } /** * Represents an edge in the graph with a start node, end node, and weight. */ private static class Edge { private int from; private int to; private int weight; Edge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } public int getFrom() { return from; } public int getTo() { return to; } public int getWeight() { return weight; } } /** * Contains information about the path and its total distance. */ static class PathAndDistance { private int distance; // total distance from the start node private ArrayList<Integer> path; // list of nodes in the path private int estimated; // heuristic estimate for reaching the destination PathAndDistance(int distance, ArrayList<Integer> path, int estimated) { this.distance = distance; this.path = path; this.estimated = estimated; } public int getDistance() { return distance; } public ArrayList<Integer> getPath() { return path; } public int getEstimated() { return estimated; } } // Initializes the graph with edges defined in the input data static void initializeGraph(Graph graph, List<Integer> data) { for (int i = 0; i < data.size(); i += 4) { graph.addEdge(new Edge(data.get(i), data.get(i + 1), data.get(i + 2))); } } /** * Implements the A* pathfinding algorithm to find the shortest path from a start node to a destination node. * * @param from the starting node * @param to the destination node * @param graph the graph representation of the problem * @param heuristic the heuristic estimates for each node * @return a PathAndDistance object containing the shortest path and its distance */ public static PathAndDistance aStar(int from, int to, Graph graph, int[] heuristic) { // PriorityQueue to explore nodes based on their distance and estimated cost to reach the destination PriorityQueue<PathAndDistance> queue = new PriorityQueue<>(Comparator.comparingInt(a -> (a.getDistance() + a.getEstimated()))); // Start with the initial node queue.add(new PathAndDistance(0, new ArrayList<>(List.of(from)), heuristic[from])); boolean solutionFound = false; PathAndDistance currentData = new PathAndDistance(-1, null, -1); while (!queue.isEmpty() && !solutionFound) { currentData = queue.poll(); // get the best node from the queue int currentPosition = currentData.getPath().get(currentData.getPath().size() - 1); // current node // Check if the destination has been reached if (currentPosition == to) { solutionFound = true; } else { for (Edge edge : graph.getNeighbours(currentPosition)) { // Avoid cycles by checking if the next node is already in the path if (!currentData.getPath().contains(edge.getTo())) { ArrayList<Integer> updatedPath = new ArrayList<>(currentData.getPath()); updatedPath.add(edge.getTo()); // Update the distance and heuristic for the new path queue.add(new PathAndDistance(currentData.getDistance() + edge.getWeight(), updatedPath, heuristic[edge.getTo()])); } } } } return (solutionFound) ? currentData : new PathAndDistance(-1, null, -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/datastructures/graphs/UndirectedAdjacencyListGraph.java
src/main/java/com/thealgorithms/datastructures/graphs/UndirectedAdjacencyListGraph.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class UndirectedAdjacencyListGraph { private ArrayList<HashMap<Integer, Integer>> adjacencyList = new ArrayList<>(); /** * Adds a new node to the graph by adding an empty HashMap for its neighbors. * @return the index of the newly added node in the adjacency list */ public int addNode() { adjacencyList.add(new HashMap<>()); return adjacencyList.size() - 1; } /** * Adds an undirected edge between the origin node (@orig) and the destination node (@dest) with the specified weight. * If the edge already exists, no changes are made. * @param orig the index of the origin node * @param dest the index of the destination node * @param weight the weight of the edge between @orig and @dest * @return true if the edge was successfully added, false if the edge already exists or if any node index is invalid */ public boolean addEdge(int orig, int dest, int weight) { int numNodes = adjacencyList.size(); if (orig >= numNodes || dest >= numNodes || orig < 0 || dest < 0) { return false; } if (adjacencyList.get(orig).containsKey(dest)) { return false; } adjacencyList.get(orig).put(dest, weight); adjacencyList.get(dest).put(orig, weight); return true; } /** * Returns the set of all adjacent nodes (neighbors) for the given node. * @param node the index of the node whose neighbors are to be retrieved * @return a HashSet containing the indices of all neighboring nodes */ public HashSet<Integer> getNeighbors(int node) { return new HashSet<>(adjacencyList.get(node).keySet()); } /** * Returns the weight of the edge between the origin node (@orig) and the destination node (@dest). * If no edge exists, returns null. * @param orig the index of the origin node * @param dest the index of the destination node * @return the weight of the edge between @orig and @dest, or null if no edge exists */ public Integer getEdgeWeight(int orig, int dest) { return adjacencyList.get(orig).getOrDefault(dest, null); } /** * Returns the number of nodes currently in the graph. * @return the number of nodes in the graph */ public int size() { return adjacencyList.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/graphs/KahnsAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/KahnsAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Set; /** * A class representing the adjacency list of a directed graph. The adjacency list * maintains a mapping of vertices to their adjacent vertices. * * @param <E> the type of vertices, extending Comparable to ensure that vertices * can be compared */ class AdjacencyList<E extends Comparable<E>> { Map<E, ArrayList<E>> adj; /** * Constructor to initialize the adjacency list. */ AdjacencyList() { adj = new LinkedHashMap<>(); } /** * Adds a directed edge from one vertex to another in the adjacency list. * If the vertex does not exist, it will be added to the list. * * @param from the starting vertex of the directed edge * @param to the destination vertex of the directed edge */ void addEdge(E from, E to) { if (!adj.containsKey(from)) { adj.put(from, new ArrayList<>()); } adj.get(from).add(to); if (!adj.containsKey(to)) { adj.put(to, new ArrayList<>()); } } /** * Retrieves the list of adjacent vertices for a given vertex. * * @param v the vertex whose adjacent vertices are to be fetched * @return an ArrayList of adjacent vertices for vertex v */ ArrayList<E> getAdjacents(E v) { return adj.get(v); } /** * Retrieves the set of all vertices present in the graph. * * @return a set containing all vertices in the graph */ Set<E> getVertices() { return adj.keySet(); } } /** * A class that performs topological sorting on a directed graph using Kahn's algorithm. * * @param <E> the type of vertices, extending Comparable to ensure that vertices * can be compared */ class TopologicalSort<E extends Comparable<E>> { AdjacencyList<E> graph; Map<E, Integer> inDegree; /** * Constructor to initialize the topological sorting class with a given graph. * * @param graph the directed graph represented as an adjacency list */ TopologicalSort(AdjacencyList<E> graph) { this.graph = graph; } /** * Calculates the in-degree of all vertices in the graph. The in-degree is * the number of edges directed into a vertex. */ void calculateInDegree() { inDegree = new HashMap<>(); for (E vertex : graph.getVertices()) { inDegree.putIfAbsent(vertex, 0); for (E adjacent : graph.getAdjacents(vertex)) { inDegree.put(adjacent, inDegree.getOrDefault(adjacent, 0) + 1); } } } /** * Returns an ArrayList containing the vertices of the graph arranged in * topological order. Topological sorting ensures that for any directed edge * (u, v), vertex u appears before vertex v in the ordering. * * @return an ArrayList of vertices in topological order * @throws IllegalStateException if the graph contains a cycle */ ArrayList<E> topSortOrder() { calculateInDegree(); Queue<E> q = new LinkedList<>(); for (var entry : inDegree.entrySet()) { if (entry.getValue() == 0) { q.add(entry.getKey()); } } ArrayList<E> answer = new ArrayList<>(); int processedVertices = 0; while (!q.isEmpty()) { E current = q.poll(); answer.add(current); processedVertices++; for (E adjacent : graph.getAdjacents(current)) { inDegree.put(adjacent, inDegree.get(adjacent) - 1); if (inDegree.get(adjacent) == 0) { q.add(adjacent); } } } if (processedVertices != graph.getVertices().size()) { throw new IllegalStateException("Graph contains a cycle, topological sort not possible"); } return answer; } } /** * A driver class that sorts a given graph in topological order using Kahn's algorithm. */ public final class KahnsAlgorithm { private KahnsAlgorithm() { } public static void main(String[] args) { // Graph definition and initialization AdjacencyList<String> graph = new AdjacencyList<>(); graph.addEdge("a", "b"); graph.addEdge("c", "a"); graph.addEdge("a", "d"); graph.addEdge("b", "d"); graph.addEdge("c", "u"); graph.addEdge("u", "b"); TopologicalSort<String> topSort = new TopologicalSort<>(graph); // Printing the topological order for (String s : topSort.topSortOrder()) { System.out.print(s + " "); } } }
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/graphs/FordFulkerson.java
src/main/java/com/thealgorithms/datastructures/graphs/FordFulkerson.java
package com.thealgorithms.datastructures.graphs; import java.util.LinkedList; import java.util.Queue; /** * This class implements the Ford-Fulkerson algorithm to compute the maximum flow * in a flow network. * * <p>The algorithm uses breadth-first search (BFS) to find augmenting paths from * the source vertex to the sink vertex, updating the flow in the network until * no more augmenting paths can be found.</p> */ public final class FordFulkerson { private static final int INF = Integer.MAX_VALUE; private FordFulkerson() { } /** * Computes the maximum flow in a flow network using the Ford-Fulkerson algorithm. * * @param vertexCount the number of vertices in the flow network * @param capacity a 2D array representing the capacity of edges in the network * @param flow a 2D array representing the current flow in the network * @param source the source vertex in the flow network * @param sink the sink vertex in the flow network * @return the total maximum flow from the source to the sink */ public static int networkFlow(int vertexCount, int[][] capacity, int[][] flow, int source, int sink) { int totalFlow = 0; while (true) { int[] parent = new int[vertexCount]; boolean[] visited = new boolean[vertexCount]; Queue<Integer> queue = new LinkedList<>(); queue.add(source); visited[source] = true; parent[source] = -1; while (!queue.isEmpty() && !visited[sink]) { int current = queue.poll(); for (int next = 0; next < vertexCount; next++) { if (!visited[next] && capacity[current][next] - flow[current][next] > 0) { queue.add(next); visited[next] = true; parent[next] = current; } } } if (!visited[sink]) { break; // No more augmenting paths } int pathFlow = INF; for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; pathFlow = Math.min(pathFlow, capacity[u][v] - flow[u][v]); } for (int v = sink; v != source; v = parent[v]) { int u = parent[v]; flow[u][v] += pathFlow; flow[v][u] -= pathFlow; } totalFlow += pathFlow; } return totalFlow; } }
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/graphs/BipartiteGraphDFS.java
src/main/java/com/thealgorithms/datastructures/graphs/BipartiteGraphDFS.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Arrays; /** * This class provides a method to check if a given undirected graph is bipartite using Depth-First Search (DFS). * A bipartite graph is a graph whose vertices can be divided into two disjoint sets such that no two vertices * within the same set are adjacent. In other words, all edges must go between the two sets. * * The implementation leverages DFS to attempt to color the graph using two colors. If we can color the graph such * that no two adjacent vertices have the same color, the graph is bipartite. * * Example: * Input (Adjacency Matrix): * {{0, 1, 0, 1}, * {1, 0, 1, 0}, * {0, 1, 0, 1}, * {1, 0, 1, 0}} * * Output: YES (This graph is bipartite) * * Input (Adjacency Matrix): * {{0, 1, 1, 0}, * {1, 0, 1, 0}, * {1, 1, 0, 1}, * {0, 0, 1, 0}} * * Output: NO (This graph is not bipartite) */ public final class BipartiteGraphDFS { private BipartiteGraphDFS() { } /** * Helper method to perform DFS and check if the graph is bipartite. * * During DFS traversal, this method attempts to color each vertex in such a way * that no two adjacent vertices share the same color. * * @param v Number of vertices in the graph * @param adj Adjacency list of the graph where each index i contains a list of adjacent vertices * @param color Array to store the color assigned to each vertex (-1 indicates uncolored) * @param node Current vertex being processed * @return True if the graph (or component of the graph) is bipartite, otherwise false */ private static boolean bipartite(int v, ArrayList<ArrayList<Integer>> adj, int[] color, int node) { if (color[node] == -1) { color[node] = 1; } for (Integer it : adj.get(node)) { if (color[it] == -1) { color[it] = 1 - color[node]; if (!bipartite(v, adj, color, it)) { return false; } } else if (color[it] == color[node]) { return false; } } return true; } /** * Method to check if the graph is bipartite. * * @param v Number of vertices in the graph * @param adj Adjacency list of the graph * @return True if the graph is bipartite, otherwise false */ public static boolean isBipartite(int v, ArrayList<ArrayList<Integer>> adj) { int[] color = new int[v + 1]; Arrays.fill(color, -1); for (int i = 0; i < v; i++) { if (color[i] == -1) { if (!bipartite(v, adj, color, i)) { return false; } } } return true; } }
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/graphs/EdmondsBlossomAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/EdmondsBlossomAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * The EdmondsBlossomAlgorithm class implements Edmonds' Blossom Algorithm * to find the maximum matching in a general graph. The algorithm efficiently * handles cases where the graph contains odd-length cycles by contracting * "blossoms" and finding augmenting paths. *<p> * <a href="https://stanford.edu/~rezab/classes/cme323/S16/projects_reports/shoemaker_vare.pdf">Documentation of Algorithm (Stanford University)</a> * <p></p> * <a href="https://en.wikipedia.org/wiki/Blossom_algorithm">Wikipedia Documentation</a> */ public final class EdmondsBlossomAlgorithm { private EdmondsBlossomAlgorithm() { } private static final int UNMATCHED = -1; // Constant to represent unmatched vertices /** * Finds the maximum matching in a general graph (Edmonds Blossom Algorithm). * * @param edges A list of edges in the graph. * @param vertexCount The number of vertices in the graph. * @return A list of matched pairs of vertices. */ public static List<int[]> maximumMatching(Iterable<int[]> edges, int vertexCount) { List<List<Integer>> graph = new ArrayList<>(vertexCount); // Initialize each vertex's adjacency list. for (int i = 0; i < vertexCount; i++) { graph.add(new ArrayList<>()); } // Populate the graph with the edges for (int[] edge : edges) { int u = edge[0]; int v = edge[1]; graph.get(u).add(v); graph.get(v).add(u); } // Initial matching array and auxiliary data structures int[] match = new int[vertexCount]; Arrays.fill(match, UNMATCHED); // All vertices are initially unmatched int[] parent = new int[vertexCount]; int[] base = new int[vertexCount]; boolean[] inBlossom = new boolean[vertexCount]; // Indicates if a vertex is part of a blossom boolean[] inQueue = new boolean[vertexCount]; // Tracks vertices in the BFS queue // Main logic for finding maximum matching for (int u = 0; u < vertexCount; u++) { if (match[u] == UNMATCHED) { // BFS initialization Arrays.fill(parent, UNMATCHED); for (int i = 0; i < vertexCount; i++) { base[i] = i; // Each vertex is its own base initially } Arrays.fill(inBlossom, false); Arrays.fill(inQueue, false); Queue<Integer> queue = new LinkedList<>(); queue.add(u); inQueue[u] = true; boolean augmentingPathFound = false; // BFS to find augmenting paths while (!queue.isEmpty() && !augmentingPathFound) { int current = queue.poll(); // Use a different name for clarity for (int y : graph.get(current)) { // Skip if we are looking at the same edge as the current match if (match[current] == y) { continue; } if (base[current] == base[y]) { continue; // Avoid self-loops } if (parent[y] == UNMATCHED) { // Case 1: y is unmatched, we've found an augmenting path if (match[y] == UNMATCHED) { parent[y] = current; augmentingPathFound = true; updateMatching(match, parent, y); // Augment along this path break; } // Case 2: y is matched, add y's match to the queue int z = match[y]; parent[y] = current; parent[z] = y; if (!inQueue[z]) { queue.add(z); inQueue[z] = true; } } else { // Case 3: Both x and y have a parent; check for a cycle/blossom int baseU = findBase(base, parent, current, y); if (baseU != UNMATCHED) { contractBlossom(new BlossomData(new BlossomAuxData(queue, parent, base, inBlossom, match, inQueue), current, y, baseU)); } } } } } } // Create result list of matched pairs List<int[]> matchingResult = new ArrayList<>(); for (int v = 0; v < vertexCount; v++) { if (match[v] != UNMATCHED && v < match[v]) { matchingResult.add(new int[] {v, match[v]}); } } return matchingResult; } /** * Updates the matching along the augmenting path found. * * @param match The matching array. * @param parent The parent array used during the BFS. * @param u The starting node of the augmenting path. */ private static void updateMatching(int[] match, int[] parent, int u) { while (u != UNMATCHED) { int v = parent[u]; int next = match[v]; match[v] = u; match[u] = v; u = next; } } /** * Finds the base of a node in the blossom. * * @param base The base array. * @param parent The parent array. * @param u One end of the edge. * @param v The other end of the edge. * @return The base of the node or UNMATCHED. */ private static int findBase(int[] base, int[] parent, int u, int v) { boolean[] visited = new boolean[base.length]; // Mark ancestors of u int currentU = u; while (true) { currentU = base[currentU]; // Move assignment out of the condition visited[currentU] = true; if (parent[currentU] == UNMATCHED) { break; } currentU = parent[currentU]; // Move assignment out of the condition } // Find the common ancestor of v int currentV = v; while (true) { currentV = base[currentV]; // Move assignment out of the condition if (visited[currentV]) { return currentV; } currentV = parent[currentV]; // Move assignment out of the condition } } /** * Contracts a blossom and updates the base array. * * @param blossomData The data containing the parameters related to the blossom contraction. */ private static void contractBlossom(BlossomData blossomData) { for (int x = blossomData.u; blossomData.auxData.base[x] != blossomData.lca; x = blossomData.auxData.parent[blossomData.auxData.match[x]]) { int baseX = blossomData.auxData.base[x]; int matchBaseX = blossomData.auxData.base[blossomData.auxData.match[x]]; // Split the inner assignment into two separate assignments blossomData.auxData.inBlossom[baseX] = true; blossomData.auxData.inBlossom[matchBaseX] = true; } for (int x = blossomData.v; blossomData.auxData.base[x] != blossomData.lca; x = blossomData.auxData.parent[blossomData.auxData.match[x]]) { int baseX = blossomData.auxData.base[x]; int matchBaseX = blossomData.auxData.base[blossomData.auxData.match[x]]; // Split the inner assignment into two separate assignments blossomData.auxData.inBlossom[baseX] = true; blossomData.auxData.inBlossom[matchBaseX] = true; } // Update the base for all marked vertices for (int i = 0; i < blossomData.auxData.base.length; i++) { if (blossomData.auxData.inBlossom[blossomData.auxData.base[i]]) { blossomData.auxData.base[i] = blossomData.lca; // Contract to the lowest common ancestor if (!blossomData.auxData.inQueue[i]) { blossomData.auxData.queue.add(i); // Add to queue if not already present blossomData.auxData.inQueue[i] = true; } } } } /** * Auxiliary data class to encapsulate common parameters for the blossom operations. */ static class BlossomAuxData { Queue<Integer> queue; // Queue for BFS traversal int[] parent; // Parent array to store the paths int[] base; // Base array to track the base of each vertex boolean[] inBlossom; // Flags to indicate if a vertex is in a blossom int[] match; // Array to store matches for each vertex boolean[] inQueue; // Flags to track vertices in the BFS queue BlossomAuxData(Queue<Integer> queue, int[] parent, int[] base, boolean[] inBlossom, int[] match, boolean[] inQueue) { this.queue = queue; this.parent = parent; this.base = base; this.inBlossom = inBlossom; this.match = match; this.inQueue = inQueue; } } /** * BlossomData class with reduced parameters. */ static class BlossomData { BlossomAuxData auxData; // Use the auxiliary data class int u; // One vertex in the edge int v; // Another vertex in the edge int lca; // Lowest Common Ancestor BlossomData(BlossomAuxData auxData, int u, int v, int lca) { this.auxData = auxData; this.u = u; this.v = v; this.lca = lca; } } }
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/graphs/JohnsonsAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/JohnsonsAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class implements Johnson's algorithm for finding all-pairs shortest paths in a weighted, * directed graph that may contain negative edge weights. * * Johnson's algorithm works by using the Bellman-Ford algorithm to compute a transformation of the * input graph that removes all negative weights, allowing Dijkstra's algorithm to be used for * efficient shortest path computations. * * Time Complexity: O(V^2 * log(V) + V*E) * Space Complexity: O(V^2) * * Where V is the number of vertices and E is the number of edges in the graph. * * For more information, please visit {@link https://en.wikipedia.org/wiki/Johnson%27s_algorithm} */ public final class JohnsonsAlgorithm { private static final double INF = Double.POSITIVE_INFINITY; private JohnsonsAlgorithm() { } /** * Executes Johnson's algorithm on the given graph. * Steps: * 1. Add a new vertex to the graph and run Bellman-Ford to compute modified weights * 2. t the graph using the modified weights * 3. Run Dijkstra's algorithm for each vertex to compute the shortest paths * The final result is a 2D array of shortest distances between all pairs of vertices. * * @param graph The input graph represented as an adjacency matrix. * @return A 2D array representing the shortest distances between all pairs of vertices. */ public static double[][] johnsonAlgorithm(double[][] graph) { int numVertices = graph.length; double[][] edges = convertToEdgeList(graph); double[] modifiedWeights = bellmanFord(edges, numVertices); double[][] reweightedGraph = reweightGraph(graph, modifiedWeights); double[][] shortestDistances = new double[numVertices][numVertices]; for (int source = 0; source < numVertices; source++) { shortestDistances[source] = dijkstra(reweightedGraph, source, modifiedWeights); } return shortestDistances; } /** * Converts the adjacency matrix representation of the graph to an edge list. * * @param graph The input graph as an adjacency matrix. * @return An array of edges, where each edge is represented as [from, to, weight]. */ public static double[][] convertToEdgeList(double[][] graph) { int numVertices = graph.length; List<double[]> edgeList = new ArrayList<>(); for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { if (i != j && !Double.isInfinite(graph[i][j])) { // Only add edges that are not self-loops and have a finite weight edgeList.add(new double[] {i, j, graph[i][j]}); } } } return edgeList.toArray(new double[0][]); } /** * Implements the Bellman-Ford algorithm to compute the shortest paths from a new vertex * to all other vertices. This is used to calculate the weight function h(v) for reweighting. * * @param edges The edge list of the graph. * @param numVertices The number of vertices in the original graph. * @return An array of modified weights for each vertex. */ private static double[] bellmanFord(double[][] edges, int numVertices) { double[] dist = new double[numVertices + 1]; Arrays.fill(dist, INF); dist[numVertices] = 0; // Add edges from the new vertex to all original vertices double[][] allEdges = Arrays.copyOf(edges, edges.length + numVertices); for (int i = 0; i < numVertices; i++) { allEdges[edges.length + i] = new double[] {numVertices, i, 0}; } // Relax all edges V times for (int i = 0; i < numVertices; i++) { for (double[] edge : allEdges) { int u = (int) edge[0]; int v = (int) edge[1]; double weight = edge[2]; if (dist[u] != INF && dist[u] + weight < dist[v]) { dist[v] = dist[u] + weight; } } } // Check for negative weight cycles for (double[] edge : allEdges) { int u = (int) edge[0]; int v = (int) edge[1]; double weight = edge[2]; if (dist[u] + weight < dist[v]) { throw new IllegalArgumentException("Graph contains a negative weight cycle"); } } return Arrays.copyOf(dist, numVertices); } /** * Reweights the graph using the modified weights computed by Bellman-Ford. * * @param graph The original graph. * @param modifiedWeights The modified weights from Bellman-Ford. * @return The reweighted graph. */ public static double[][] reweightGraph(double[][] graph, double[] modifiedWeights) { int numVertices = graph.length; double[][] reweightedGraph = new double[numVertices][numVertices]; for (int i = 0; i < numVertices; i++) { for (int j = 0; j < numVertices; j++) { if (graph[i][j] != 0) { // New weight = original weight + h(u) - h(v) reweightedGraph[i][j] = graph[i][j] + modifiedWeights[i] - modifiedWeights[j]; } } } return reweightedGraph; } /** * Implements Dijkstra's algorithm for finding shortest paths from a source vertex. * * @param reweightedGraph The reweighted graph to run Dijkstra's on. * @param source The source vertex. * @param modifiedWeights The modified weights from Bellman-Ford. * @return An array of shortest distances from the source to all other vertices. */ public static double[] dijkstra(double[][] reweightedGraph, int source, double[] modifiedWeights) { int numVertices = reweightedGraph.length; double[] dist = new double[numVertices]; boolean[] visited = new boolean[numVertices]; Arrays.fill(dist, INF); dist[source] = 0; for (int count = 0; count < numVertices - 1; count++) { int u = minDistance(dist, visited); visited[u] = true; for (int v = 0; v < numVertices; v++) { if (!visited[v] && reweightedGraph[u][v] != 0 && dist[u] != INF && dist[u] + reweightedGraph[u][v] < dist[v]) { dist[v] = dist[u] + reweightedGraph[u][v]; } } } // Adjust distances back to the original graph weights for (int i = 0; i < numVertices; i++) { if (dist[i] != INF) { dist[i] = dist[i] - modifiedWeights[source] + modifiedWeights[i]; } } return dist; } /** * Finds the vertex with the minimum distance value from the set of vertices * not yet included in the shortest path tree. * * @param dist Array of distances. * @param visited Array of visited vertices. * @return The index of the vertex with minimum distance. */ public static int minDistance(double[] dist, boolean[] visited) { double min = INF; int minIndex = -1; for (int v = 0; v < dist.length; v++) { if (!visited[v] && dist[v] <= min) { min = dist[v]; minIndex = v; } } return minIndex; } }
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/graphs/DijkstraOptimizedAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/DijkstraOptimizedAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import org.apache.commons.lang3.tuple.Pair; /** * Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph. */ public class DijkstraOptimizedAlgorithm { private final int vertexCount; /** * Constructs a Dijkstra object with the given number of vertices. * * @param vertexCount The number of vertices in the graph. */ public DijkstraOptimizedAlgorithm(int vertexCount) { this.vertexCount = vertexCount; } /** * Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices. * * The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i} * to vertex {@code j}. A value of 0 indicates no edge exists between the vertices. * * @param graph The graph represented as an adjacency matrix. * @param source The source vertex. * @return An array where the value at each index {@code i} represents the shortest distance from the source vertex to vertex {@code i}. * @throws IllegalArgumentException if the source vertex is out of range. */ public int[] run(int[][] graph, int source) { if (source < 0 || source >= vertexCount) { throw new IllegalArgumentException("Incorrect source"); } int[] distances = new int[vertexCount]; boolean[] processed = new boolean[vertexCount]; Set<Pair<Integer, Integer>> unprocessed = new TreeSet<>(); Arrays.fill(distances, Integer.MAX_VALUE); Arrays.fill(processed, false); distances[source] = 0; unprocessed.add(Pair.of(0, source)); while (!unprocessed.isEmpty()) { Pair<Integer, Integer> distanceAndU = unprocessed.iterator().next(); unprocessed.remove(distanceAndU); int u = distanceAndU.getRight(); processed[u] = true; for (int v = 0; v < vertexCount; v++) { if (!processed[v] && graph[u][v] != 0 && distances[u] != Integer.MAX_VALUE && distances[u] + graph[u][v] < distances[v]) { unprocessed.remove(Pair.of(distances[v], v)); distances[v] = distances[u] + graph[u][v]; unprocessed.add(Pair.of(distances[v], v)); } } } return distances; } }
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/graphs/WelshPowell.java
src/main/java/com/thealgorithms/datastructures/graphs/WelshPowell.java
package com.thealgorithms.datastructures.graphs; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.stream.IntStream; /** * The Welsh-Powell algorithm is a graph coloring algorithm that aims to color a graph * using the minimum number of colors such that no two adjacent vertices share the same color. * * <p> * The algorithm works by: * <ol> * <li>Sorting the vertices in descending order based on their degrees (number of edges connected).</li> * <li>Iterating through each vertex and assigning it the smallest available color that has not been used by its adjacent vertices.</li> * <li>Coloring adjacent vertices with the same color is avoided.</li> * </ol> * </p> * * <p> * For more information, see <a href="https://en.wikipedia.org/wiki/Graph_coloring">Graph Coloring</a>. * </p> */ @SuppressWarnings({"rawtypes", "unchecked"}) public final class WelshPowell { private static final int BLANK_COLOR = -1; // Constant representing an uncolored state private WelshPowell() { } /** * Represents a graph using an adjacency list. */ static final class Graph { private final HashSet<Integer>[] adjacencyLists; /** * Initializes a graph with a specified number of vertices. * * @param vertices the number of vertices in the graph * @throws IllegalArgumentException if the number of vertices is negative */ private Graph(int vertices) { if (vertices < 0) { throw new IllegalArgumentException("Number of vertices cannot be negative"); } adjacencyLists = new HashSet[vertices]; Arrays.setAll(adjacencyLists, i -> new HashSet<>()); } /** * Adds an edge between two vertices in the graph. * * @param nodeA one end of the edge * @param nodeB the other end of the edge * @throws IllegalArgumentException if the vertices are out of bounds or if a self-loop is attempted */ private void addEdge(int nodeA, int nodeB) { validateVertex(nodeA); validateVertex(nodeB); if (nodeA == nodeB) { throw new IllegalArgumentException("Self-loops are not allowed"); } adjacencyLists[nodeA].add(nodeB); adjacencyLists[nodeB].add(nodeA); } /** * Validates that the vertex index is within the bounds of the graph. * * @param vertex the index of the vertex to validate * @throws IllegalArgumentException if the vertex is out of bounds */ private void validateVertex(int vertex) { if (vertex < 0 || vertex >= getNumVertices()) { throw new IllegalArgumentException("Vertex " + vertex + " is out of bounds"); } } /** * Returns the adjacency list for a specific vertex. * * @param vertex the index of the vertex * @return the set of adjacent vertices */ HashSet<Integer> getAdjacencyList(int vertex) { return adjacencyLists[vertex]; } /** * Returns the number of vertices in the graph. * * @return the number of vertices */ int getNumVertices() { return adjacencyLists.length; } } /** * Creates a graph with the specified number of vertices and edges. * * @param numberOfVertices the total number of vertices * @param listOfEdges a 2D array representing edges where each inner array contains two vertex indices * @return a Graph object representing the created graph * @throws IllegalArgumentException if the edge array is invalid or vertices are out of bounds */ public static Graph makeGraph(int numberOfVertices, int[][] listOfEdges) { Graph graph = new Graph(numberOfVertices); for (int[] edge : listOfEdges) { if (edge.length != 2) { throw new IllegalArgumentException("Edge array must have exactly two elements"); } graph.addEdge(edge[0], edge[1]); } return graph; } /** * Finds the coloring of the given graph using the Welsh-Powell algorithm. * * @param graph the input graph to color * @return an array of integers where each index represents a vertex and the value represents the color assigned */ public static int[] findColoring(Graph graph) { int[] colors = initializeColors(graph.getNumVertices()); Integer[] sortedVertices = getSortedNodes(graph); for (int vertex : sortedVertices) { if (isBlank(colors[vertex])) { boolean[] usedColors = computeUsedColors(graph, vertex, colors); final var newColor = firstUnusedColor(usedColors); colors[vertex] = newColor; Arrays.stream(sortedVertices).forEach(otherVertex -> { if (isBlank(colors[otherVertex]) && !isAdjacentToColored(graph, otherVertex, colors)) { colors[otherVertex] = newColor; } }); } } return colors; } /** * Helper method to check if a color is unassigned * * @param color the color to check * @return {@code true} if the color is unassigned, {@code false} otherwise */ private static boolean isBlank(int color) { return color == BLANK_COLOR; } /** * Checks if a vertex has adjacent colored vertices * * @param graph the input graph * @param vertex the vertex to check * @param colors the array of colors assigned to the vertices * @return {@code true} if the vertex has adjacent colored vertices, {@code false} otherwise */ private static boolean isAdjacentToColored(Graph graph, int vertex, int[] colors) { return graph.getAdjacencyList(vertex).stream().anyMatch(otherVertex -> !isBlank(colors[otherVertex])); } /** * Initializes the colors array with blank color * * @param numberOfVertices the number of vertices in the graph * @return an array of integers representing the colors assigned to the vertices */ private static int[] initializeColors(int numberOfVertices) { int[] colors = new int[numberOfVertices]; Arrays.fill(colors, BLANK_COLOR); return colors; } /** * Sorts the vertices by their degree in descending order * * @param graph the input graph * @return an array of integers representing the vertices sorted by degree */ private static Integer[] getSortedNodes(final Graph graph) { return IntStream.range(0, graph.getNumVertices()).boxed().sorted(Comparator.comparingInt(v -> - graph.getAdjacencyList(v).size())).toArray(Integer[] ::new); } /** * Computes the colors already used by the adjacent vertices * * @param graph the input graph * @param vertex the vertex to check * @param colors the array of colors assigned to the vertices * @return an array of booleans representing the colors used by the adjacent vertices */ private static boolean[] computeUsedColors(final Graph graph, final int vertex, final int[] colors) { boolean[] usedColors = new boolean[graph.getNumVertices()]; graph.getAdjacencyList(vertex).stream().map(neighbor -> colors[neighbor]).filter(color -> !isBlank(color)).forEach(color -> usedColors[color] = true); return usedColors; } /** * Finds the first unused color * * @param usedColors the array of colors used by the adjacent vertices * @return the first unused color */ private static int firstUnusedColor(boolean[] usedColors) { return IntStream.range(0, usedColors.length).filter(color -> !usedColors[color]).findFirst().getAsInt(); } }
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/graphs/Kosaraju.java
src/main/java/com/thealgorithms/datastructures/graphs/Kosaraju.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * This class implements the Kosaraju Algorithm to find all the Strongly Connected Components (SCCs) * of a directed graph. Kosaraju's algorithm runs in linear time and leverages the concept that * the SCCs of a directed graph remain the same in its transpose (reverse) graph. * * <p> * A strongly connected component (SCC) of a directed graph is a subgraph where every vertex * is reachable from every other vertex in the subgraph. The Kosaraju algorithm is particularly * efficient for finding SCCs because it performs two Depth First Search (DFS) passes on the * graph and its transpose. * </p> * * <p><strong>Algorithm:</strong></p> * <ol> * <li>Perform DFS on the original graph and push nodes to a stack in the order of their finishing time.</li> * <li>Generate the transpose (reversed edges) of the original graph.</li> * <li>Perform DFS on the transpose graph, using the stack from the first DFS. Each DFS run on the transpose graph gives a SCC.</li> * </ol> * * <p><strong>Example Graph:</strong></p> * <pre> * 0 <--- 2 -------> 3 -------- > 4 ---- > 7 * | ^ | ^ ^ * | / | \ / * | / | \ / * v / v \ / * 1 5 --> 6 * </pre> * * <p><strong>SCCs in the example:</strong></p> * <ul> * <li>{0, 1, 2}</li> * <li>{3}</li> * <li>{4, 5, 6}</li> * <li>{7}</li> * </ul> * * <p>The order of nodes in an SCC does not matter because every node in an SCC is reachable from every other node within the same SCC.</p> * * <p><strong>Graph Transpose Example:</strong></p> * <pre> * 0 ---> 2 <------- 3 <------- 4 <------ 7 * ^ / ^ \ / * | / | \ / * | / | \ / * | v | v v * 1 5 <--- 6 * </pre> * * The SCCs of this transpose graph are the same as the original graph. */ public class Kosaraju { // Stack to sort edges by the lowest finish time (used in the first DFS) private final Stack<Integer> stack = new Stack<>(); // Store each strongly connected component private List<Integer> scc = new ArrayList<>(); // List of all SCCs private final List<List<Integer>> sccsList = new ArrayList<>(); /** * Main function to perform Kosaraju's Algorithm. * Steps: * 1. Sort nodes by the lowest finishing time * 2. Create the transpose (reverse edges) of the original graph * 3. Find SCCs by performing DFS on the transpose graph * 4. Return the list of SCCs * * @param v the number of vertices in the graph * @param list the adjacency list representing the directed graph * @return a list of SCCs where each SCC is a list of vertices */ public List<List<Integer>> kosaraju(int v, List<List<Integer>> list) { sortEdgesByLowestFinishTime(v, list); List<List<Integer>> transposeGraph = createTransposeMatrix(v, list); findStronglyConnectedComponents(v, transposeGraph); return sccsList; } /** * Performs DFS on the original graph to sort nodes by their finishing times. * @param v the number of vertices in the graph * @param list the adjacency list representing the original graph */ private void sortEdgesByLowestFinishTime(int v, List<List<Integer>> list) { int[] vis = new int[v]; for (int i = 0; i < v; i++) { if (vis[i] == 0) { dfs(i, vis, list); } } } /** * Creates the transpose (reverse) of the original graph. * @param v the number of vertices in the graph * @param list the adjacency list representing the original graph * @return the adjacency list representing the transposed graph */ private List<List<Integer>> createTransposeMatrix(int v, List<List<Integer>> list) { List<List<Integer>> transposeGraph = new ArrayList<>(v); for (int i = 0; i < v; i++) { transposeGraph.add(new ArrayList<>()); } for (int i = 0; i < v; i++) { for (Integer neigh : list.get(i)) { transposeGraph.get(neigh).add(i); } } return transposeGraph; } /** * Finds the strongly connected components (SCCs) by performing DFS on the transposed graph. * @param v the number of vertices in the graph * @param transposeGraph the adjacency list representing the transposed graph */ public void findStronglyConnectedComponents(int v, List<List<Integer>> transposeGraph) { int[] vis = new int[v]; while (!stack.isEmpty()) { int node = stack.pop(); if (vis[node] == 0) { dfs2(node, vis, transposeGraph); sccsList.add(scc); scc = new ArrayList<>(); } } } /** * Performs DFS on the original graph and pushes nodes onto the stack in order of their finish time. * @param node the current node being visited * @param vis array to keep track of visited nodes * @param list the adjacency list of the graph */ private void dfs(int node, int[] vis, List<List<Integer>> list) { vis[node] = 1; for (Integer neighbour : list.get(node)) { if (vis[neighbour] == 0) { dfs(neighbour, vis, list); } } stack.push(node); } /** * Performs DFS on the transposed graph to find the strongly connected components. * @param node the current node being visited * @param vis array to keep track of visited nodes * @param list the adjacency list of the transposed graph */ private void dfs2(int node, int[] vis, List<List<Integer>> list) { vis[node] = 1; for (Integer neighbour : list.get(node)) { if (vis[neighbour] == 0) { dfs2(neighbour, vis, list); } } scc.add(node); } }
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/graphs/BellmanFord.java
src/main/java/com/thealgorithms/datastructures/graphs/BellmanFord.java
package com.thealgorithms.datastructures.graphs; import java.util.Scanner; class BellmanFord /* * Implementation of Bellman ford to detect negative cycles. Graph accepts * inputs * in form of edges which have start vertex, end vertex and weights. Vertices * should be labelled with a * number between 0 and total number of vertices-1,both inclusive */ { int vertex; int edge; private Edge[] edges; private int index = 0; BellmanFord(int v, int e) { vertex = v; edge = e; edges = new Edge[e]; } class Edge { int u; int v; int w; /** * @param u Source Vertex * @param v End vertex * @param c Weight */ Edge(int a, int b, int c) { u = a; v = b; w = c; } } /** * @param p[] Parent array which shows updates in edges * @param i Current vertex under consideration */ void printPath(int[] p, int i) { if (p[i] == -1) { // Found the path back to parent return; } printPath(p, p[i]); System.out.print(i + " "); } public static void main(String[] args) { BellmanFord obj = new BellmanFord(0, 0); // Dummy object to call nonstatic variables obj.go(); } public void go() { // shows distance to all vertices // Interactive run for understanding the // class first time. Assumes source vertex is 0 and try (Scanner sc = new Scanner(System.in)) { int i; int v; int e; int u; int ve; int w; int j; int neg = 0; System.out.println("Enter no. of vertices and edges please"); v = sc.nextInt(); e = sc.nextInt(); Edge[] arr = new Edge[e]; // Array of edges System.out.println("Input edges"); for (i = 0; i < e; i++) { u = sc.nextInt(); ve = sc.nextInt(); w = sc.nextInt(); arr[i] = new Edge(u, ve, w); } int[] dist = new int[v]; // Distance array for holding the finalized shortest path distance // between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { dist[i] = Integer.MAX_VALUE; // Initializing distance values } dist[0] = 0; p[0] = -1; for (i = 0; i < v - 1; i++) { for (j = 0; j < e; j++) { if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update p[arr[j].v] = arr[j].u; } } } // Final cycle for negative checking for (j = 0; j < e; j++) { if (dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { neg = 1; System.out.println("Negative cycle"); break; } } if (neg == 0) { // Go ahead and show results of computation System.out.println("Distances are: "); for (i = 0; i < v; i++) { System.out.println(i + " " + dist[i]); } System.out.println("Path followed:"); for (i = 0; i < v; i++) { System.out.print("0 "); printPath(p, i); System.out.println(); } } } } /** * @param source Starting vertex * @param end Ending vertex * @param Edge Array of edges */ public void show(int source, int end, Edge[] arr) { // be created by using addEdge() method and passed by calling getEdgeArray() // method // Just shows results of computation, if graph is passed to it. The // graph should int i; int j; int v = vertex; int e = edge; int neg = 0; double[] dist = new double[v]; // Distance array for holding the finalized shortest path // distance between source // and all vertices int[] p = new int[v]; // Parent array for holding the paths for (i = 0; i < v; i++) { dist[i] = Integer.MAX_VALUE; // Initializing distance values } dist[source] = 0; p[source] = -1; for (i = 0; i < v - 1; i++) { for (j = 0; j < e; j++) { if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { dist[arr[j].v] = dist[arr[j].u] + arr[j].w; // Update p[arr[j].v] = arr[j].u; } } } // Final cycle for negative checking for (j = 0; j < e; j++) { if ((int) dist[arr[j].u] != Integer.MAX_VALUE && dist[arr[j].v] > dist[arr[j].u] + arr[j].w) { neg = 1; System.out.println("Negative cycle"); break; } } if (neg == 0) { // Go ahead and show results of computation System.out.println("Distance is: " + dist[end]); System.out.println("Path followed:"); System.out.print(source + " "); printPath(p, end); System.out.println(); } } /** * @param x Source Vertex * @param y End vertex * @param z Weight */ public void addEdge(int x, int y, int z) { // Adds unidirectional edge edges[index++] = new Edge(x, y, z); } public Edge[] getEdgeArray() { return edges; } }
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/graphs/BoruvkaAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/BoruvkaAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.List; /** * Boruvka's algorithm to find Minimum Spanning Tree * (https://en.wikipedia.org/wiki/Bor%C5%AFvka%27s_algorithm) * * @author itakurah (https://github.com/itakurah) */ final class BoruvkaAlgorithm { private BoruvkaAlgorithm() { } /** * Represents an edge in the graph */ static class Edge { final int src; final int dest; final int weight; Edge(final int src, final int dest, final int weight) { this.src = src; this.dest = dest; this.weight = weight; } } /** * Represents the graph */ static class Graph { final int vertex; final List<Edge> edges; /** * Constructor for the graph * * @param vertex number of vertices * @param edges list of edges */ Graph(final int vertex, final List<Edge> edges) { if (vertex < 0) { throw new IllegalArgumentException("Number of vertices must be positive"); } if (edges == null || edges.isEmpty()) { throw new IllegalArgumentException("Edges list must not be null or empty"); } for (final var edge : edges) { checkEdgeVertices(edge.src, vertex); checkEdgeVertices(edge.dest, vertex); } this.vertex = vertex; this.edges = edges; } } /** * Represents a subset for Union-Find operations */ private static class Component { int parent; int rank; Component(final int parent, final int rank) { this.parent = parent; this.rank = rank; } } /** * Represents the state of Union-Find components and the result list */ private static class BoruvkaState { List<Edge> result; Component[] components; final Graph graph; BoruvkaState(final Graph graph) { this.result = new ArrayList<>(); this.components = initializeComponents(graph); this.graph = graph; } /** * Adds the cheapest edges to the result list and performs Union operation on the subsets. * * @param cheapest Array containing the cheapest edge for each subset. */ void merge(final Edge[] cheapest) { for (int i = 0; i < graph.vertex; ++i) { if (cheapest[i] != null) { final var component1 = find(components, cheapest[i].src); final var component2 = find(components, cheapest[i].dest); if (component1 != component2) { result.add(cheapest[i]); union(components, component1, component2); } } } } /** * Checks if there are more edges to add to the result list * * @return true if there are more edges to add, false otherwise */ boolean hasMoreEdgesToAdd() { return result.size() < graph.vertex - 1; } /** * Computes the cheapest edges for each subset in the Union-Find structure. * * @return an array containing the cheapest edge for each subset. */ private Edge[] computeCheapestEdges() { Edge[] cheapest = new Edge[graph.vertex]; for (final var edge : graph.edges) { final var set1 = find(components, edge.src); final var set2 = find(components, edge.dest); if (set1 != set2) { if (cheapest[set1] == null || edge.weight < cheapest[set1].weight) { cheapest[set1] = edge; } if (cheapest[set2] == null || edge.weight < cheapest[set2].weight) { cheapest[set2] = edge; } } } return cheapest; } /** * Initializes subsets for Union-Find * * @param graph the graph * @return the initialized subsets */ private static Component[] initializeComponents(final Graph graph) { Component[] components = new Component[graph.vertex]; for (int v = 0; v < graph.vertex; ++v) { components[v] = new Component(v, 0); } return components; } } /** * Finds the parent of the subset using path compression * * @param components array of subsets * @param i index of the subset * @return the parent of the subset */ static int find(final Component[] components, final int i) { if (components[i].parent != i) { components[i].parent = find(components, components[i].parent); } return components[i].parent; } /** * Performs the Union operation for Union-Find * * @param components array of subsets * @param x index of the first subset * @param y index of the second subset */ static void union(Component[] components, final int x, final int y) { final int xroot = find(components, x); final int yroot = find(components, y); if (components[xroot].rank < components[yroot].rank) { components[xroot].parent = yroot; } else if (components[xroot].rank > components[yroot].rank) { components[yroot].parent = xroot; } else { components[yroot].parent = xroot; components[xroot].rank++; } } /** * Boruvka's algorithm to find the Minimum Spanning Tree * * @param graph the graph * @return list of edges in the Minimum Spanning Tree */ static List<Edge> boruvkaMST(final Graph graph) { var boruvkaState = new BoruvkaState(graph); while (boruvkaState.hasMoreEdgesToAdd()) { final var cheapest = boruvkaState.computeCheapestEdges(); boruvkaState.merge(cheapest); } return boruvkaState.result; } /** * Checks if the edge vertices are in a valid range * * @param vertex the vertex to check * @param upperBound the upper bound for the vertex range */ private static void checkEdgeVertices(final int vertex, final int upperBound) { if (vertex < 0 || vertex >= upperBound) { throw new IllegalArgumentException("Edge vertex out of range"); } } }
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/graphs/DijkstraAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/DijkstraAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.Arrays; /** * Dijkstra's algorithm for finding the shortest path from a single source vertex to all other vertices in a graph. */ public class DijkstraAlgorithm { private final int vertexCount; /** * Constructs a Dijkstra object with the given number of vertices. * * @param vertexCount The number of vertices in the graph. */ public DijkstraAlgorithm(int vertexCount) { this.vertexCount = vertexCount; } /** * Executes Dijkstra's algorithm on the provided graph to find the shortest paths from the source vertex to all other vertices. * * The graph is represented as an adjacency matrix where {@code graph[i][j]} represents the weight of the edge from vertex {@code i} * to vertex {@code j}. A value of 0 indicates no edge exists between the vertices. * * @param graph The graph represented as an adjacency matrix. * @param source The source vertex. * @return An array where the value at each index {@code i} represents the shortest distance from the source vertex to vertex {@code i}. * @throws IllegalArgumentException if the source vertex is out of range. */ public int[] run(int[][] graph, int source) { if (source < 0 || source >= vertexCount) { throw new IllegalArgumentException("Incorrect source"); } int[] distances = new int[vertexCount]; boolean[] processed = new boolean[vertexCount]; Arrays.fill(distances, Integer.MAX_VALUE); Arrays.fill(processed, false); distances[source] = 0; for (int count = 0; count < vertexCount - 1; count++) { int u = getMinDistanceVertex(distances, processed); processed[u] = true; for (int v = 0; v < vertexCount; v++) { if (!processed[v] && graph[u][v] != 0 && distances[u] != Integer.MAX_VALUE && distances[u] + graph[u][v] < distances[v]) { distances[v] = distances[u] + graph[u][v]; } } } printDistances(distances); return distances; } /** * Finds the vertex with the minimum distance value from the set of vertices that have not yet been processed. * * @param distances The array of current shortest distances from the source vertex. * @param processed The array indicating whether each vertex has been processed. * @return The index of the vertex with the minimum distance value. */ private int getMinDistanceVertex(int[] distances, boolean[] processed) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int v = 0; v < vertexCount; v++) { if (!processed[v] && distances[v] <= min) { min = distances[v]; minIndex = v; } } return minIndex; } /** * Prints the shortest distances from the source vertex to all other vertices. * * @param distances The array of shortest distances. */ private void printDistances(int[] distances) { System.out.println("Vertex \t Distance"); for (int i = 0; i < vertexCount; i++) { System.out.println(i + " \t " + distances[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/graphs/FloydWarshall.java
src/main/java/com/thealgorithms/datastructures/graphs/FloydWarshall.java
package com.thealgorithms.datastructures.graphs; /** * The {@code FloydWarshall} class provides an implementation of the Floyd-Warshall algorithm * to compute the shortest paths between all pairs of vertices in a weighted graph. * It handles both positive and negative edge weights but does not support negative cycles. * The algorithm is based on dynamic programming and runs in O(V^3) time complexity, * where V is the number of vertices in the graph. * * <p> * The distance matrix is updated iteratively to find the shortest distance between any two vertices * by considering each vertex as an intermediate step. * </p> * * Reference: <a href="https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm">Floyd-Warshall Algorithm</a> */ public class FloydWarshall { private int[][] distanceMatrix; private int numberofvertices; public static final int INFINITY = 999; /** * Constructs a Floyd-Warshall instance for a graph with the given number of vertices. * Initializes the distance matrix for the graph. * * @param numberofvertices The number of vertices in the graph. */ public FloydWarshall(int numberofvertices) { distanceMatrix = new int[numberofvertices + 1][numberofvertices + 1]; // The matrix is initialized with 0's by default this.numberofvertices = numberofvertices; } /** * Executes the Floyd-Warshall algorithm to compute the shortest path between all pairs of vertices. * It uses an adjacency matrix to calculate the distance matrix by considering each vertex as an intermediate point. * * @param adjacencyMatrix The weighted adjacency matrix representing the graph. * A value of 0 means no direct edge between the vertices, except for diagonal elements which are 0 (distance to self). */ public void floydwarshall(int[][] adjacencyMatrix) { // Initialize the distance matrix with the adjacency matrix. for (int source = 1; source <= numberofvertices; source++) { System.arraycopy(adjacencyMatrix[source], 1, distanceMatrix[source], 1, numberofvertices); } for (int intermediate = 1; intermediate <= numberofvertices; intermediate++) { for (int source = 1; source <= numberofvertices; source++) { for (int destination = 1; destination <= numberofvertices; destination++) { // Update distance if a shorter path through the intermediate vertex exists. if (distanceMatrix[source][intermediate] + distanceMatrix[intermediate][destination] < distanceMatrix[source][destination]) { distanceMatrix[source][destination] = distanceMatrix[source][intermediate] + distanceMatrix[intermediate][destination]; } } } } printDistanceMatrix(); } /** * Prints the distance matrix representing the shortest paths between all pairs of vertices. * The rows and columns correspond to the source and destination vertices. */ private void printDistanceMatrix() { // Print header for vertices for (int source = 1; source <= numberofvertices; source++) { System.out.print("\t" + source); } System.out.println(); // Print the distance matrix for (int source = 1; source <= numberofvertices; source++) { System.out.print(source + "\t"); for (int destination = 1; destination <= numberofvertices; destination++) { System.out.print(distanceMatrix[source][destination] + "\t"); } System.out.println(); } } public Object[] getDistanceMatrix() { return distanceMatrix; } }
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/graphs/DialsAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/DialsAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * An implementation of Dial's Algorithm for the single-source shortest path problem. * This algorithm is an optimization of Dijkstra's algorithm and is particularly * efficient for graphs with small, non-negative integer edge weights. * * It uses a bucket queue (implemented here as a List of HashSets) to store vertices, * where each bucket corresponds to a specific distance from the source. This is more * efficient than a standard priority queue when the range of edge weights is small. * * Time Complexity: O(E + W * V), where E is the number of edges, V is the number * of vertices, and W is the maximum weight of any edge. * * @see <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Dial's_algorithm">Wikipedia - Dial's Algorithm</a> */ public final class DialsAlgorithm { /** * Private constructor to prevent instantiation of this utility class. */ private DialsAlgorithm() { } /** * Represents an edge in the graph, connecting to a destination vertex with a given weight. */ public static class Edge { private final int destination; private final int weight; public Edge(int destination, int weight) { this.destination = destination; this.weight = weight; } public int getDestination() { return destination; } public int getWeight() { return weight; } } /** * Finds the shortest paths from a source vertex to all other vertices in a weighted graph. * * @param graph The graph represented as an adjacency list. * @param source The source vertex to start from (0-indexed). * @param maxEdgeWeight The maximum weight of any single edge in the graph. * @return An array of integers where the value at each index `i` is the * shortest distance from the source to vertex `i`. Unreachable vertices * will have a value of Integer.MAX_VALUE. * @throws IllegalArgumentException if the source vertex is out of bounds. */ public static int[] run(List<List<Edge>> graph, int source, int maxEdgeWeight) { int numVertices = graph.size(); if (source < 0 || source >= numVertices) { throw new IllegalArgumentException("Source vertex is out of bounds."); } // Initialize distances array int[] distances = new int[numVertices]; Arrays.fill(distances, Integer.MAX_VALUE); distances[source] = 0; // The bucket queue. Size is determined by the max possible path length. int maxPathWeight = maxEdgeWeight * (numVertices > 0 ? numVertices - 1 : 0); List<Set<Integer>> buckets = new ArrayList<>(maxPathWeight + 1); for (int i = 0; i <= maxPathWeight; i++) { buckets.add(new HashSet<>()); } // Add the source vertex to the first bucket buckets.get(0).add(source); // Process buckets in increasing order of distance for (int d = 0; d <= maxPathWeight; d++) { // Process all vertices in the current bucket while (!buckets.get(d).isEmpty()) { // Get and remove a vertex from the current bucket int u = buckets.get(d).iterator().next(); buckets.get(d).remove(u); // If we've found a shorter path already, skip if (d > distances[u]) { continue; } // Relax all adjacent edges for (Edge edge : graph.get(u)) { int v = edge.getDestination(); int weight = edge.getWeight(); // If a shorter path to v is found if (distances[u] != Integer.MAX_VALUE && distances[u] + weight < distances[v]) { // If v was already in a bucket, remove it from the old one if (distances[v] != Integer.MAX_VALUE) { buckets.get(distances[v]).remove(v); } // Update distance and move v to the new bucket distances[v] = distances[u] + weight; buckets.get(distances[v]).add(v); } } } } return distances; } }
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/graphs/PrimMST.java
src/main/java/com/thealgorithms/datastructures/graphs/PrimMST.java
package com.thealgorithms.datastructures.graphs; /** * A Java program for Prim's Minimum Spanning Tree (MST) algorithm. * Adjacency matrix representation of the graph. */ public class PrimMST { // Number of vertices in the graph private static final int V = 5; // A utility function to find the vertex with the minimum key // value, from the set of vertices not yet included in the MST int minKey(int[] key, Boolean[] mstSet) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int v = 0; v < V; v++) { if (!mstSet[v] && key[v] < min) { min = key[v]; minIndex = v; } } return minIndex; } // Function to construct MST for a graph using adjacency matrix representation public int[] primMST(int[][] graph) { int[] parent = new int[V]; // Array to store constructed MST int[] key = new int[V]; // Key values to pick minimum weight edge Boolean[] mstSet = new Boolean[V]; // Vertices not yet included in MST // Initialize all keys as INFINITE and mstSet[] as false for (int i = 0; i < V; i++) { key[i] = Integer.MAX_VALUE; mstSet[i] = Boolean.FALSE; } // Always include the first vertex in MST key[0] = 0; // Make key 0 to pick the first vertex parent[0] = -1; // First node is always root of MST // The MST will have V vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum key vertex not yet included in MST int u = minKey(key, mstSet); mstSet[u] = Boolean.TRUE; // Update key value and parent index of adjacent vertices of the picked vertex for (int v = 0; v < V; v++) { if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) { parent[v] = u; key[v] = graph[u][v]; } } } return parent; // Return the MST parent array } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
src/main/java/com/thealgorithms/datastructures/graphs/HamiltonianCycle.java
package com.thealgorithms.datastructures.graphs; import java.util.Arrays; /** * Java program to find a Hamiltonian Cycle in a graph. * A Hamiltonian Cycle is a cycle that visits every vertex exactly once * and returns to the starting vertex. * * <p>For more details, see the * <a href="https://en.wikipedia.org/wiki/Hamiltonian_path">Wikipedia article</a>. * * @author <a href="https://github.com/itsAkshayDubey">Akshay Dubey</a> */ public class HamiltonianCycle { private int vertex; private int pathCount; private int[] cycle; private int[][] graph; /** * Finds a Hamiltonian Cycle for the given graph. * * @param graph Adjacency matrix representing the graph G(V, E), where V is * the set of vertices and E is the set of edges. * @return An array representing the Hamiltonian cycle if found, otherwise an * array filled with -1 indicating no Hamiltonian cycle exists. */ public int[] findHamiltonianCycle(int[][] graph) { // Single vertex graph if (graph.length == 1) { return new int[] {0, 0}; } this.vertex = graph.length; this.cycle = new int[this.vertex + 1]; // Initialize the cycle array with -1 to represent unvisited vertices Arrays.fill(this.cycle, -1); this.graph = graph; this.cycle[0] = 0; this.pathCount = 1; if (!isPathFound(0)) { Arrays.fill(this.cycle, -1); } else { this.cycle[this.cycle.length - 1] = this.cycle[0]; } return cycle; } /** * Recursively searches for a Hamiltonian cycle from the given vertex. * * @param vertex The current vertex from which to explore paths. * @return {@code true} if a Hamiltonian cycle is found, otherwise {@code false}. */ public boolean isPathFound(int vertex) { boolean isLastVertexConnectedToStart = this.graph[vertex][0] == 1 && this.pathCount == this.vertex; if (isLastVertexConnectedToStart) { return true; } // If all vertices are visited but the last vertex is not connected to the start if (this.pathCount == this.vertex) { return false; } for (int v = 0; v < this.vertex; v++) { if (this.graph[vertex][v] == 1) { // Check if there is an edge this.cycle[this.pathCount++] = v; // Add the vertex to the cycle this.graph[vertex][v] = 0; this.graph[v][vertex] = 0; // Recursively attempt to complete the cycle if (!isPresent(v)) { return isPathFound(v); } // Restore the edge if the path does not work this.graph[vertex][v] = 1; this.graph[v][vertex] = 1; this.cycle[--this.pathCount] = -1; } } return false; } /** * Checks if a vertex is already part of the current Hamiltonian path. * * @param vertex The vertex to check. * @return {@code true} if the vertex is already in the path, otherwise {@code false}. */ public boolean isPresent(int vertex) { for (int i = 0; i < pathCount - 1; i++) { if (cycle[i] == vertex) { 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/graphs/TwoSat.java
src/main/java/com/thealgorithms/datastructures/graphs/TwoSat.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Arrays; import java.util.Stack; /** * This class implements a solution to the 2-SAT (2-Satisfiability) problem * using Kosaraju's algorithm to find strongly connected components (SCCs) * in the implication graph. * * <p> * <strong>Brief Idea:</strong> * </p> * * <pre> * 1. From each clause (a ∨ b), we can derive implications: * (¬a → b) and (¬b → a) * * 2. We construct an implication graph using these implications. * * 3. For each variable x, its negation ¬x is also represented as a node. * If x and ¬x belong to the same SCC, the expression is unsatisfiable. * * 4. Otherwise, we assign truth values based on the SCC order: * If SCC(x) > SCC(¬x), then x = true; otherwise, x = false. * </pre> * * <p> * <strong>Complexities:</strong> * </p> * <ul> * <li>Time Complexity: O(n + m)</li> * <li>Space Complexity: O(n + m)</li> * </ul> * where {@code n} is the number of variables and {@code m} is the number of * clauses. * * <p> * <strong>Usage Example:</strong> * </p> * * <pre> * TwoSat twoSat = new TwoSat(5); // Initialize with 5 variables: x1, x2, x3, x4, x5 * * // Add clauses * twoSat.addClause(1, false, 2, false); // (x1 ∨ x2) * twoSat.addClause(3, true, 2, false); // (¬x3 ∨ x2) * twoSat.addClause(4, false, 5, true); // (x4 ∨ ¬x5) * * twoSat.solve(); // Solve the problem * * if (twoSat.isSolutionExists()) { * boolean[] solution = twoSat.getSolutions(); * for (int i = 1; i <= 5; i++) { * System.out.println("x" + i + " = " + solution[i]); * } * } * </pre> * <p><strong>Reference</strong></p> * <a href="https://cp-algorithms.com/graph/2SAT.html">CP Algorithm</a> <br></br> * <a href="https://en.wikipedia.org/wiki/2-satisfiability">Wikipedia - 2 SAT</a> * @author Shoyeb Ansari * * @see Kosaraju */ class TwoSat { /** Number of variables in the boolean expression. */ private final int numberOfVariables; /** Implication graph built from the boolean clauses. */ private final ArrayList<Integer>[] graph; /** Transposed implication graph used in Kosaraju's algorithm. */ private final ArrayList<Integer>[] graphTranspose; /** Stores one valid truth assignment for all variables (1-indexed). */ private final boolean[] variableAssignments; /** Indicates whether a valid solution exists. */ private boolean hasSolution = true; /** Tracks whether the {@code solve()} method has been called. */ private boolean isSolved = false; /** * Initializes the TwoSat solver with the given number of variables. * * @param numberOfVariables the number of boolean variables * @throws IllegalArgumentException if the number of variables is negative */ @SuppressWarnings({"unchecked", "rawtypes"}) TwoSat(int numberOfVariables) { if (numberOfVariables < 0) { throw new IllegalArgumentException("Number of variables cannot be negative."); } this.numberOfVariables = numberOfVariables; int n = 2 * numberOfVariables + 1; graph = (ArrayList<Integer>[]) new ArrayList[n]; graphTranspose = (ArrayList<Integer>[]) new ArrayList[n]; for (int i = 0; i < n; i++) { graph[i] = new ArrayList<>(); graphTranspose[i] = new ArrayList<>(); } variableAssignments = new boolean[numberOfVariables + 1]; } /** * Adds a clause of the form (a ∨ b) to the boolean expression. * * <p> * Example: To add (¬x₁ ∨ x₂), call: * </p> * * <pre>{@code * addClause(1, true, 2, false); * }</pre> * * @param a the first variable (1 ≤ a ≤ numberOfVariables) * @param isNegateA {@code true} if variable {@code a} is negated * @param b the second variable (1 ≤ b ≤ numberOfVariables) * @param isNegateB {@code true} if variable {@code b} is negated * @throws IllegalArgumentException if {@code a} or {@code b} are out of range */ void addClause(int a, boolean isNegateA, int b, boolean isNegateB) { if (a <= 0 || a > numberOfVariables) { throw new IllegalArgumentException("Variable number must be between 1 and " + numberOfVariables); } if (b <= 0 || b > numberOfVariables) { throw new IllegalArgumentException("Variable number must be between 1 and " + numberOfVariables); } a = isNegateA ? negate(a) : a; b = isNegateB ? negate(b) : b; int notA = negate(a); int notB = negate(b); // Add implications: (¬a → b) and (¬b → a) graph[notA].add(b); graph[notB].add(a); // Build transpose graph graphTranspose[b].add(notA); graphTranspose[a].add(notB); } /** * Solves the 2-SAT problem using Kosaraju's algorithm to find SCCs * and determines whether a satisfying assignment exists. */ void solve() { isSolved = true; int n = 2 * numberOfVariables + 1; boolean[] visited = new boolean[n]; int[] component = new int[n]; Stack<Integer> topologicalOrder = new Stack<>(); // Step 1: Perform DFS to get topological order for (int i = 1; i < n; i++) { if (!visited[i]) { dfsForTopologicalOrder(i, visited, topologicalOrder); } } Arrays.fill(visited, false); int sccId = 0; // Step 2: Find SCCs on transposed graph while (!topologicalOrder.isEmpty()) { int node = topologicalOrder.pop(); if (!visited[node]) { dfsForScc(node, visited, component, sccId); sccId++; } } // Step 3: Check for contradictions and assign values for (int i = 1; i <= numberOfVariables; i++) { int notI = negate(i); if (component[i] == component[notI]) { hasSolution = false; return; } // If SCC(i) > SCC(¬i), then variable i is true. variableAssignments[i] = component[i] > component[notI]; } } /** * Returns whether the given boolean formula is satisfiable. * * @return {@code true} if a solution exists; {@code false} otherwise * @throws Error if called before {@link #solve()} */ boolean isSolutionExists() { if (!isSolved) { throw new Error("Please call solve() before checking for a solution."); } return hasSolution; } /** * Returns one valid assignment of variables that satisfies the boolean formula. * * @return a boolean array where {@code result[i]} represents the truth value of * variable {@code xᵢ} * @throws Error if called before {@link #solve()} or if no solution exists */ boolean[] getSolutions() { if (!isSolved) { throw new Error("Please call solve() before fetching the solution."); } if (!hasSolution) { throw new Error("No satisfying assignment exists for the given expression."); } return variableAssignments.clone(); } /** Performs DFS to compute topological order. */ private void dfsForTopologicalOrder(int u, boolean[] visited, Stack<Integer> topologicalOrder) { visited[u] = true; for (int v : graph[u]) { if (!visited[v]) { dfsForTopologicalOrder(v, visited, topologicalOrder); } } topologicalOrder.push(u); } /** Performs DFS on the transposed graph to identify SCCs. */ private void dfsForScc(int u, boolean[] visited, int[] component, int sccId) { visited[u] = true; component[u] = sccId; for (int v : graphTranspose[u]) { if (!visited[v]) { dfsForScc(v, visited, component, sccId); } } } /** * Returns the index representing the negation of the given variable. * * <p> * Mapping rule: * </p> * * <pre> * For a variable i: * negate(i) = i + n * For a negated variable (i + n): * negate(i + n) = i * where n = numberOfVariables * </pre> * * @param a the variable index * @return the index representing its negation */ private int negate(int a) { return a <= numberOfVariables ? a + numberOfVariables : a - numberOfVariables; } }
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/graphs/ConnectedComponent.java
src/main/java/com/thealgorithms/datastructures/graphs/ConnectedComponent.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** * A class that counts the number of different connected components in a graph * * @author Lukas Keul, Florian Mercks */ class Graph<E extends Comparable<E>> { class Node { E name; Node(E name) { this.name = name; } } class Edge { Node startNode; Node endNode; Edge(Node startNode, Node endNode) { this.startNode = startNode; this.endNode = endNode; } } ArrayList<Edge> edgeList; ArrayList<Node> nodeList; Graph() { edgeList = new ArrayList<Edge>(); nodeList = new ArrayList<Node>(); } /** * Adds a new Edge to the graph. If the nodes aren't yet in nodeList, they * will be added to it. * * @param startNode the starting Node from the edge * @param endNode the ending Node from the edge */ public void addEdge(E startNode, E endNode) { Node start = null; Node end = null; for (Node node : nodeList) { if (startNode.compareTo(node.name) == 0) { start = node; } else if (endNode.compareTo(node.name) == 0) { end = node; } } if (start == null) { start = new Node(startNode); nodeList.add(start); } if (end == null) { end = new Node(endNode); nodeList.add(end); } edgeList.add(new Edge(start, end)); } /** * Main method used for counting the connected components. Iterates through * the array of nodes to do a depth first search to get all nodes of the * graph from the actual node. These nodes are added to the array * markedNodes and will be ignored if they are chosen in the nodeList. * * @return returns the amount of unconnected graphs */ public int countGraphs() { int count = 0; Set<Node> markedNodes = new HashSet<Node>(); for (Node n : nodeList) { if (markedNodes.add(n)) { markedNodes.addAll(depthFirstSearch(n, new ArrayList<Node>())); count++; } } return count; } /** * Implementation of depth first search. * * @param n the actual visiting node * @param visited A list of already visited nodes in the depth first search * @return returns a set of visited nodes */ public ArrayList<Node> depthFirstSearch(Node n, ArrayList<Node> visited) { visited.add(n); for (Edge e : edgeList) { if (e.startNode.equals(n) && !visited.contains(e.endNode)) { depthFirstSearch(e.endNode, visited); } } return visited; } } public final class ConnectedComponent { private ConnectedComponent() { } public static void main(String[] args) { Graph<Character> graphChars = new Graph<>(); // Graph 1 graphChars.addEdge('a', 'b'); graphChars.addEdge('a', 'e'); graphChars.addEdge('b', 'e'); graphChars.addEdge('b', 'c'); graphChars.addEdge('c', 'd'); graphChars.addEdge('d', 'a'); graphChars.addEdge('x', 'y'); graphChars.addEdge('x', 'z'); graphChars.addEdge('w', 'w'); Graph<Integer> graphInts = new Graph<>(); // Graph 2 graphInts.addEdge(1, 2); graphInts.addEdge(2, 3); graphInts.addEdge(2, 4); graphInts.addEdge(3, 5); graphInts.addEdge(7, 8); graphInts.addEdge(8, 10); graphInts.addEdge(10, 8); System.out.println("Amount of different char-graphs: " + graphChars.countGraphs()); System.out.println("Amount of different int-graphs: " + graphInts.countGraphs()); } }
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/graphs/Graphs.java
src/main/java/com/thealgorithms/datastructures/graphs/Graphs.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; class AdjacencyListGraph<E extends Comparable<E>> { ArrayList<Vertex> vertices; AdjacencyListGraph() { vertices = new ArrayList<>(); } private class Vertex { E data; ArrayList<Vertex> adjacentVertices; Vertex(E data) { adjacentVertices = new ArrayList<>(); this.data = data; } public boolean addAdjacentVertex(Vertex to) { for (Vertex v : adjacentVertices) { if (v.data.compareTo(to.data) == 0) { return false; // the edge already exists } } return adjacentVertices.add(to); // this will return true; } public boolean removeAdjacentVertex(E to) { // use indexes here so it is possible to // remove easily without implementing // equals method that ArrayList.remove(Object o) uses for (int i = 0; i < adjacentVertices.size(); i++) { if (adjacentVertices.get(i).data.compareTo(to) == 0) { adjacentVertices.remove(i); return true; } } return false; } } /** * this method removes an edge from the graph between two specified * vertices * * @param from the data of the vertex the edge is from * @param to the data of the vertex the edge is going to * @return returns false if the edge doesn't exist, returns true if the edge * exists and is removed */ public boolean removeEdge(E from, E to) { Vertex fromV = null; for (Vertex v : vertices) { if (from.compareTo(v.data) == 0) { fromV = v; break; } } if (fromV == null) { return false; } return fromV.removeAdjacentVertex(to); } /** * this method adds an edge to the graph between two specified vertices * * @param from the data of the vertex the edge is from * @param to the data of the vertex the edge is going to * @return returns true if the edge did not exist, return false if it * already did */ public boolean addEdge(E from, E to) { Vertex fromV = null; Vertex toV = null; for (Vertex v : vertices) { if (from.compareTo(v.data) == 0) { // see if from vertex already exists fromV = v; } else if (to.compareTo(v.data) == 0) { // see if to vertex already exists toV = v; } if (fromV != null && toV != null) { break; // both nodes exist so stop searching } } if (fromV == null) { fromV = new Vertex(from); vertices.add(fromV); } if (toV == null) { toV = new Vertex(to); vertices.add(toV); } return fromV.addAdjacentVertex(toV); } /** * this gives a list of vertices in the graph and their adjacencies * * @return returns a string describing this graph */ @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Vertex v : vertices) { sb.append("Vertex: "); sb.append(v.data); sb.append("\n"); sb.append("Adjacent vertices: "); for (Vertex v2 : v.adjacentVertices) { sb.append(v2.data); sb.append(" "); } sb.append("\n"); } return sb.toString(); } } public final class Graphs { private Graphs() { } public static void main(String[] args) { AdjacencyListGraph<Integer> graph = new AdjacencyListGraph<>(); assert graph.addEdge(1, 2); assert graph.addEdge(1, 5); assert graph.addEdge(2, 5); assert !graph.addEdge(1, 2); assert graph.addEdge(2, 3); assert graph.addEdge(3, 4); assert graph.addEdge(4, 1); assert !graph.addEdge(2, 3); System.out.println(graph); } }
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/graphs/TarjansAlgorithm.java
src/main/java/com/thealgorithms/datastructures/graphs/TarjansAlgorithm.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** * Java program that implements Tarjan's Algorithm to find Strongly Connected Components (SCCs) in a directed graph. * * <p> * Tarjan's algorithm is a linear time algorithm (O(V + E)) that identifies the SCCs of a directed graph. * An SCC is a maximal subgraph where every vertex is reachable from every other vertex within the subgraph. * * <h3>Algorithm Overview:</h3> * <ul> * <li>DFS Search: A depth-first search (DFS) is performed on the graph to generate a DFS tree.</li> * <li>Identification of SCCs: SCCs correspond to subtrees within this DFS tree.</li> * <li>Low-Link Values: For each node, a low-link value is maintained, which indicates the earliest visited * vertex (the one with the minimum insertion time) that can be reached from that subtree.</li> * <li>Stack Usage: Nodes are stored in a stack during DFS. When an SCC is identified, nodes are popped from * the stack until the head of the SCC is reached.</li> * </ul> * * <p> * Example of a directed graph: * <pre> * 0 --------> 1 -------> 3 --------> 4 * ^ / * | / * | / * | / * | / * | / * | / * | / * | / * | / * V * 2 * </pre> * * <p> * For the above graph, the SCC list is as follows: * <ul> * <li>1, 2, 0</li> * <li>3</li> * <li>4</li> * </ul> * The order of nodes in an SCC does not matter as they form cycles. * * <h3>Comparison with Kosaraju's Algorithm:</h3> * <p> * Kosaraju's algorithm also identifies SCCs but does so using two DFS traversals. * In contrast, Tarjan's algorithm achieves this in a single DFS traversal, leading to improved performance * in terms of constant factors. * </p> */ public class TarjansAlgorithm { // Timer for tracking low time and insertion time private int time; // List to store all strongly connected components private final List<List<Integer>> sccList = new ArrayList<>(); /** * Finds and returns the strongly connected components (SCCs) of the directed graph. * * @param v the number of vertices in the graph * @param graph the adjacency list representation of the graph * @return a list of lists, where each inner list represents a strongly connected component */ public List<List<Integer>> stronglyConnectedComponents(int v, List<List<Integer>> graph) { // Initialize arrays for insertion time and low-link values int[] lowTime = new int[v]; int[] insertionTime = new int[v]; for (int i = 0; i < v; i++) { insertionTime[i] = -1; lowTime[i] = -1; } // Track if vertices are in the stack boolean[] isInStack = new boolean[v]; // Stack to hold nodes during DFS Stack<Integer> st = new Stack<>(); for (int i = 0; i < v; i++) { if (insertionTime[i] == -1) { stronglyConnCompsUtil(i, lowTime, insertionTime, isInStack, st, graph); } } return sccList; } /** * A utility function to perform DFS and find SCCs. * * @param u the current vertex being visited * @param lowTime array to keep track of the low-link values * @param insertionTime array to keep track of the insertion times * @param isInStack boolean array indicating if a vertex is in the stack * @param st the stack used for DFS * @param graph the adjacency list representation of the graph */ private void stronglyConnCompsUtil(int u, int[] lowTime, int[] insertionTime, boolean[] isInStack, Stack<Integer> st, List<List<Integer>> graph) { // Set insertion time and low-link value insertionTime[u] = time; lowTime[u] = time; time++; // Push current node onto the stack isInStack[u] = true; st.push(u); // Explore adjacent vertices for (Integer vertex : graph.get(u)) { if (insertionTime[vertex] == -1) { stronglyConnCompsUtil(vertex, lowTime, insertionTime, isInStack, st, graph); // Update low-link value lowTime[u] = Math.min(lowTime[u], lowTime[vertex]); } else if (isInStack[vertex]) { // Vertex is in the stack; update low-link value lowTime[u] = Math.min(lowTime[u], insertionTime[vertex]); } } // Check if the current vertex is the root of an SCC if (lowTime[u] == insertionTime[u]) { int w = -1; List<Integer> scc = new ArrayList<>(); // Pop vertices from the stack until the root is found while (w != u) { w = st.pop(); scc.add(w); isInStack[w] = false; } sccList.add(scc); } } }
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/graphs/Cycles.java
src/main/java/com/thealgorithms/datastructures/graphs/Cycles.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.Scanner; class Cycle { private final int nodes; private int[][] adjacencyMatrix; private boolean[] visited; ArrayList<ArrayList<Integer>> cycles = new ArrayList<ArrayList<Integer>>(); Cycle() { Scanner in = new Scanner(System.in); System.out.print("Enter the no. of nodes: "); nodes = in.nextInt(); System.out.print("Enter the no. of Edges: "); final int edges = in.nextInt(); adjacencyMatrix = new int[nodes][nodes]; visited = new boolean[nodes]; for (int i = 0; i < nodes; i++) { visited[i] = false; } System.out.println("Enter the details of each edges <Start Node> <End Node>"); for (int i = 0; i < edges; i++) { int start; int end; start = in.nextInt(); end = in.nextInt(); adjacencyMatrix[start][end] = 1; } in.close(); } public void start() { for (int i = 0; i < nodes; i++) { ArrayList<Integer> temp = new ArrayList<>(); dfs(i, i, temp); for (int j = 0; j < nodes; j++) { adjacencyMatrix[i][j] = 0; adjacencyMatrix[j][i] = 0; } } } private void dfs(Integer start, Integer curr, ArrayList<Integer> temp) { temp.add(curr); visited[curr] = true; for (int i = 0; i < nodes; i++) { if (adjacencyMatrix[curr][i] == 1) { if (i == start) { cycles.add(new ArrayList<Integer>(temp)); } else { if (!visited[i]) { dfs(start, i, temp); } } } } if (temp.size() > 0) { temp.remove(temp.size() - 1); } visited[curr] = false; } public void printAll() { for (int i = 0; i < cycles.size(); i++) { for (int j = 0; j < cycles.get(i).size(); j++) { System.out.print(cycles.get(i).get(j) + " -> "); } System.out.println(cycles.get(i).get(0)); System.out.println(); } } } public final class Cycles { private Cycles() { } public static void main(String[] args) { Cycle c = new Cycle(); c.start(); c.printAll(); } }
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/graphs/MatrixGraphs.java
src/main/java/com/thealgorithms/datastructures/graphs/MatrixGraphs.java
package com.thealgorithms.datastructures.graphs; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * Implementation of a graph in a matrix form Also known as an adjacency matrix * representation [Adjacency matrix - * Wikipedia](https://en.wikipedia.org/wiki/Adjacency_matrix) * * @author Unknown */ public final class MatrixGraphs { private MatrixGraphs() { } public static void main(String[] args) { AdjacencyMatrixGraph graph = new AdjacencyMatrixGraph(10); graph.addEdge(1, 2); graph.addEdge(1, 5); graph.addEdge(2, 5); graph.addEdge(1, 2); graph.addEdge(2, 3); graph.addEdge(3, 4); graph.addEdge(4, 1); graph.addEdge(2, 3); graph.addEdge(3, 9); graph.addEdge(9, 1); graph.addEdge(9, 8); graph.addEdge(1, 8); graph.addEdge(5, 6); System.out.println("The graph matrix:"); System.out.println(graph); System.out.println("Depth first order beginning at node '1':"); System.out.println(graph.depthFirstOrder(1)); System.out.println("Breadth first order beginning at node '1':"); System.out.println(graph.breadthFirstOrder(1)); } } /** * AdjacencyMatrixGraph Implementation */ class AdjacencyMatrixGraph { /** * The number of vertices in the graph */ private int vertexCount; /** * The number of edges in the graph */ private int edgeCount; /** * The adjacency matrix for the graph */ private int[][] adjMatrix; /** * Static variables to define whether or not an edge exists in the adjacency * matrix */ static final int EDGE_EXIST = 1; static final int EDGE_NONE = 0; /** * Constructor */ AdjacencyMatrixGraph(int givenNumberOfVertices) { this.setNumberOfVertices(givenNumberOfVertices); this.setNumberOfEdges(0); this.setAdjacency(new int[givenNumberOfVertices][givenNumberOfVertices]); for (int i = 0; i < givenNumberOfVertices; i++) { for (int j = 0; j < givenNumberOfVertices; j++) { this.adjacency()[i][j] = AdjacencyMatrixGraph.EDGE_NONE; } } } /** * Updates the number of vertices in the graph * * @param newNumberOfVertices the new number of vertices */ private void setNumberOfVertices(int newNumberOfVertices) { this.vertexCount = newNumberOfVertices; } /** * Getter for `this.vertexCount` * * @return the number of vertices in the graph */ public int numberOfVertices() { return this.vertexCount; } /** * Updates the number of edges in the graph * * @param newNumberOfEdges the new number of edges * */ private void setNumberOfEdges(int newNumberOfEdges) { this.edgeCount = newNumberOfEdges; } /** * Getter for `this.edgeCount` * * @return the number of edges */ public int numberOfEdges() { return this.edgeCount; } /** * Sets a new matrix as the adjacency matrix * * @param newAdjacency the new adjaceny matrix */ private void setAdjacency(int[][] newAdjacency) { this.adjMatrix = newAdjacency; } /** * Getter for the adjacency matrix * * @return the adjacency matrix */ private int[][] adjacency() { return this.adjMatrix; } /** * Checks if two vertices are connected by an edge * * @param from the parent vertex to check for adjacency * @param to the child vertex to check for adjacency * @return whether or not the vertices are adjacent */ private boolean adjacencyOfEdgeDoesExist(int from, int to) { return (this.adjacency()[from][to] != AdjacencyMatrixGraph.EDGE_NONE); } /** * Checks if a particular vertex exists in a graph * * @param aVertex the vertex to check for existence * @return whether or not the vertex exists */ public boolean vertexDoesExist(int aVertex) { return aVertex >= 0 && aVertex < this.numberOfVertices(); } /** * Checks if two vertices are connected by an edge * * @param from the parent vertex to check for adjacency * @param to the child vertex to check for adjacency * @return whether or not the vertices are adjacent */ public boolean edgeDoesExist(int from, int to) { if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { return (this.adjacencyOfEdgeDoesExist(from, to)); } return false; } /** * This method adds an edge to the graph between two specified vertices * * @param from the data of the vertex the edge is from * @param to the data of the vertex the edge is going to * @return returns true if the edge did not exist, return false if it * already did */ public boolean addEdge(int from, int to) { if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { if (!this.adjacencyOfEdgeDoesExist(from, to)) { this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_EXIST; this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_EXIST; this.setNumberOfEdges(this.numberOfEdges() + 1); return true; } } return false; } /** * this method removes an edge from the graph between two specified vertices * * @param from the data of the vertex the edge is from * @param to the data of the vertex the edge is going to * @return returns false if the edge doesn't exist, returns true if the edge * exists and is removed */ public boolean removeEdge(int from, int to) { if (this.vertexDoesExist(from) && this.vertexDoesExist(to)) { if (this.adjacencyOfEdgeDoesExist(from, to)) { this.adjacency()[from][to] = AdjacencyMatrixGraph.EDGE_NONE; this.adjacency()[to][from] = AdjacencyMatrixGraph.EDGE_NONE; this.setNumberOfEdges(this.numberOfEdges() - 1); return true; } } return false; } /** * This method returns a list of the vertices in a depth first order * beginning with the specified vertex * * @param startVertex the vertex to begin the traversal * @return the list of the ordered vertices */ public List<Integer> depthFirstOrder(int startVertex) { // If the startVertex is invalid, return an empty list if (startVertex >= vertexCount || startVertex < 0) { return new ArrayList<>(); } // Create an array to track the visited vertices boolean[] visited = new boolean[vertexCount]; // Create a list to keep track of the order of our traversal ArrayList<Integer> orderList = new ArrayList<>(); // Perform our DFS algorithm depthFirstOrder(startVertex, visited, orderList); return orderList; } /** * Helper method for public depthFirstOrder(int) that will perform a depth * first traversal recursively on the graph * * @param currentVertex the currently exploring vertex * @param visited the array of values denoting whether or not that vertex * has been visited * @param orderList the list to add vertices to as they are visited */ private void depthFirstOrder(int currentVertex, boolean[] visited, List<Integer> orderList) { // If this vertex has already been visited, do nothing and return if (visited[currentVertex]) { return; } // Visit the currentVertex by marking it as visited and adding it // to the orderList visited[currentVertex] = true; orderList.add(currentVertex); // Get the adjacency array for this vertex int[] adjacent = adjMatrix[currentVertex]; for (int i = 0; i < adjacent.length; i++) { // we are considering exploring, recurse on it // If an edge exists between the // currentVertex and the vertex if (adjacent[i] == AdjacencyMatrixGraph.EDGE_EXIST) { depthFirstOrder(i, visited, orderList); } } } /** * This method returns a list of the vertices in a breadth first order * beginning with the specified vertex * * @param startVertex the vertext to begin the traversal * @return the list of the ordered vertices */ public List<Integer> breadthFirstOrder(int startVertex) { // If the specified startVertex is invalid, return an empty list if (startVertex >= vertexCount || startVertex < 0) { return new ArrayList<>(); } // Create an array to keep track of the visited vertices boolean[] visited = new boolean[vertexCount]; // Create a list to keep track of the ordered vertices ArrayList<Integer> orderList = new ArrayList<>(); // Create a queue for our BFS algorithm and add the startVertex // to the queue Queue<Integer> queue = new LinkedList<>(); queue.add(startVertex); // Continue until the queue is empty while (!queue.isEmpty()) { // Remove the first vertex in the queue int currentVertex = queue.poll(); // If we've visited this vertex, skip it if (visited[currentVertex]) { continue; } // We now visit this vertex by adding it to the orderList and // marking it as visited orderList.add(currentVertex); visited[currentVertex] = true; // Get the adjacency array for the currentVertex and // check each node int[] adjacent = adjMatrix[currentVertex]; for (int vertex = 0; vertex < adjacent.length; vertex++) { // vertex we are considering exploring, we add it to the queue // If an // edge exists between the current vertex and the if (adjacent[vertex] == AdjacencyMatrixGraph.EDGE_EXIST) { queue.add(vertex); } } } return orderList; } /** * this gives a list of vertices in the graph and their adjacencies * * @return returns a string describing this graph */ public String toString() { StringBuilder s = new StringBuilder(" "); for (int i = 0; i < this.numberOfVertices(); i++) { s.append(i).append(" "); } s.append(" \n"); for (int i = 0; i < this.numberOfVertices(); i++) { s.append(i).append(" : "); for (int j = 0; j < this.numberOfVertices(); j++) { s.append(this.adjMatrix[i][j]).append(" "); } s.append("\n"); } return s.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/graphs/Kruskal.java
src/main/java/com/thealgorithms/datastructures/graphs/Kruskal.java
package com.thealgorithms.datastructures.graphs; import java.util.Comparator; import java.util.HashSet; import java.util.PriorityQueue; /** * The Kruskal class implements Kruskal's Algorithm to find the Minimum Spanning Tree (MST) * of a connected, undirected graph. The algorithm constructs the MST by selecting edges * with the least weight, ensuring no cycles are formed, and using union-find to track the * connected components. * * <p><strong>Key Features:</strong></p> * <ul> * <li>The graph is represented using an adjacency list, where each node points to a set of edges.</li> * <li>Each edge is processed in ascending order of weight using a priority queue.</li> * <li>The algorithm stops when all nodes are connected or no more edges are available.</li> * </ul> * * <p><strong>Time Complexity:</strong> O(E log V), where E is the number of edges and V is the number of vertices.</p> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class Kruskal { /** * Represents an edge in the graph with a source, destination, and weight. */ static class Edge { int from; int to; int weight; Edge(int from, int to, int weight) { this.from = from; this.to = to; this.weight = weight; } } /** * Adds an edge to the graph. * * @param graph the adjacency list representing the graph * @param from the source vertex of the edge * @param to the destination vertex of the edge * @param weight the weight of the edge */ static void addEdge(HashSet<Edge>[] graph, int from, int to, int weight) { graph[from].add(new Edge(from, to, weight)); } /** * Kruskal's algorithm to find the Minimum Spanning Tree (MST) of a graph. * * @param graph the adjacency list representing the input graph * @return the adjacency list representing the MST */ public HashSet<Edge>[] kruskal(HashSet<Edge>[] graph) { int nodes = graph.length; int[] captain = new int[nodes]; // Stores the "leader" of each node's connected component HashSet<Integer>[] connectedGroups = new HashSet[nodes]; HashSet<Edge>[] minGraph = new HashSet[nodes]; PriorityQueue<Edge> edges = new PriorityQueue<>(Comparator.comparingInt(edge -> edge.weight)); for (int i = 0; i < nodes; i++) { minGraph[i] = new HashSet<>(); connectedGroups[i] = new HashSet<>(); connectedGroups[i].add(i); captain[i] = i; edges.addAll(graph[i]); } int connectedElements = 0; while (connectedElements != nodes && !edges.isEmpty()) { Edge edge = edges.poll(); // Avoid forming cycles by checking if the nodes belong to different connected components if (!connectedGroups[captain[edge.from]].contains(edge.to) && !connectedGroups[captain[edge.to]].contains(edge.from)) { // Merge the two sets of nodes connected by the edge connectedGroups[captain[edge.from]].addAll(connectedGroups[captain[edge.to]]); // Update the captain for each merged node connectedGroups[captain[edge.from]].forEach(i -> captain[i] = captain[edge.from]); // Add the edge to the resulting MST graph addEdge(minGraph, edge.from, edge.to, edge.weight); // Update the count of connected nodes connectedElements = connectedGroups[captain[edge.from]].size(); } } return minGraph; } }
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/caches/LFUCache.java
src/main/java/com/thealgorithms/datastructures/caches/LFUCache.java
package com.thealgorithms.datastructures.caches; import java.util.HashMap; import java.util.Map; /** * The {@code LFUCache} class implements a Least Frequently Used (LFU) cache. * An LFU cache evicts the least frequently used item when the cache reaches its capacity. * It maintains a mapping of keys to nodes, where each node contains the key, its associated value, * and a frequency count that tracks how many times the item has been accessed. A doubly linked list * is used to efficiently manage the ordering of items based on their usage frequency. * * <p>This implementation is designed to provide O(1) time complexity for both the {@code get} and * {@code put} operations, which is achieved through the use of a hashmap for quick access and a * doubly linked list for maintaining the order of item frequencies.</p> * * <p> * Reference: <a href="https://en.wikipedia.org/wiki/Least_frequently_used">LFU Cache - Wikipedia</a> * </p> * * @param <K> The type of keys maintained by this cache. * @param <V> The type of mapped values. * * @author Akshay Dubey (https://github.com/itsAkshayDubey) */ public class LFUCache<K, V> { /** * The {@code Node} class represents an element in the LFU cache. * Each node contains a key, a value, and a frequency count. * It also has pointers to the previous and next nodes in the doubly linked list. */ private class Node { private final K key; private V value; private int frequency; private Node previous; private Node next; /** * Constructs a new {@code Node} with the specified key, value, and frequency. * * @param key The key associated with this node. * @param value The value stored in this node. * @param frequency The frequency of usage of this node. */ Node(K key, V value, int frequency) { this.key = key; this.value = value; this.frequency = frequency; } } private Node head; private Node tail; private final Map<K, Node> cache; private final int capacity; private static final int DEFAULT_CAPACITY = 100; /** * Constructs an LFU cache with the default capacity. */ public LFUCache() { this(DEFAULT_CAPACITY); } /** * Constructs an LFU cache with the specified capacity. * * @param capacity The maximum number of items that the cache can hold. * @throws IllegalArgumentException if the specified capacity is less than or equal to zero. */ public LFUCache(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity must be greater than zero."); } this.capacity = capacity; this.cache = new HashMap<>(); } /** * Retrieves the value associated with the given key from the cache. * If the key exists, the node's frequency is incremented, and the node is repositioned * in the linked list based on its updated frequency. * * @param key The key whose associated value is to be returned. * @return The value associated with the key, or {@code null} if the key is not present in the cache. */ public V get(K key) { Node node = cache.get(key); if (node == null) { return null; } removeNode(node); node.frequency += 1; addNodeWithUpdatedFrequency(node); return node.value; } /** * Inserts or updates a key-value pair in the cache. * If the key already exists, the value is updated and its frequency is incremented. * If the cache is full, the least frequently used item is removed before inserting the new item. * * @param key The key associated with the value to be inserted or updated. * @param value The value to be inserted or updated. */ public void put(K key, V value) { if (cache.containsKey(key)) { Node node = cache.get(key); node.value = value; node.frequency += 1; removeNode(node); addNodeWithUpdatedFrequency(node); } else { if (cache.size() >= capacity) { cache.remove(this.head.key); // Evict least frequently used item removeNode(head); } Node node = new Node(key, value, 1); addNodeWithUpdatedFrequency(node); cache.put(key, node); } } /** * Adds a node to the linked list in the correct position based on its frequency. * The linked list is ordered by frequency, with the least frequently used node at the head. * * @param node The node to be inserted into the list. */ private void addNodeWithUpdatedFrequency(Node node) { if (tail != null && head != null) { Node temp = this.head; while (true) { if (temp.frequency > node.frequency) { if (temp == head) { node.next = temp; temp.previous = node; this.head = node; break; } else { node.next = temp; node.previous = temp.previous; temp.previous.next = node; temp.previous = node; break; } } else { temp = temp.next; if (temp == null) { tail.next = node; node.previous = tail; node.next = null; tail = node; break; } } } } else { tail = node; head = tail; } } /** * Removes a node from the doubly linked list. * This method ensures that the pointers of neighboring nodes are properly updated. * * @param node The node to be removed from the list. */ private void removeNode(Node node) { if (node.previous != null) { node.previous.next = node.next; } else { this.head = node.next; } if (node.next != null) { node.next.previous = node.previous; } else { this.tail = node.previous; } } }
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/caches/LRUCache.java
src/main/java/com/thealgorithms/datastructures/caches/LRUCache.java
package com.thealgorithms.datastructures.caches; import java.util.HashMap; import java.util.Map; /** * A Least Recently Used (LRU) Cache implementation. * * <p>An LRU cache is a fixed-size cache that maintains items in order of use. When the cache reaches * its capacity and a new item needs to be added, it removes the least recently used item first. * This implementation provides O(1) time complexity for both get and put operations.</p> * * <p>Features:</p> * <ul> * <li>Fixed-size cache with configurable capacity</li> * <li>Constant time O(1) operations for get and put</li> * <li>Thread-unsafe - should be externally synchronized if used in concurrent environments</li> * <li>Supports null values but not null keys</li> * </ul> * * <p>Implementation Details:</p> * <ul> * <li>Uses a HashMap for O(1) key-value lookups</li> * <li>Maintains a doubly-linked list for tracking access order</li> * <li>The head of the list contains the least recently used item</li> * <li>The tail of the list contains the most recently used item</li> * </ul> * * <p>Example usage:</p> * <pre> * LRUCache<String, Integer> cache = new LRUCache<>(3); // Create cache with capacity 3 * cache.put("A", 1); // Cache: A=1 * cache.put("B", 2); // Cache: A=1, B=2 * cache.put("C", 3); // Cache: A=1, B=2, C=3 * cache.get("A"); // Cache: B=2, C=3, A=1 (A moved to end) * cache.put("D", 4); // Cache: C=3, A=1, D=4 (B evicted) * </pre> * * @param <K> the type of keys maintained by this cache * @param <V> the type of mapped values */ public class LRUCache<K, V> { private final Map<K, Entry<K, V>> data = new HashMap<>(); private Entry<K, V> head; private Entry<K, V> tail; private int cap; private static final int DEFAULT_CAP = 100; public LRUCache() { setCapacity(DEFAULT_CAP); } public LRUCache(int cap) { setCapacity(cap); } /** * Returns the current capacity of the cache. * * @param newCapacity the new capacity of the cache */ private void setCapacity(int newCapacity) { checkCapacity(newCapacity); for (int i = data.size(); i > newCapacity; i--) { Entry<K, V> evicted = evict(); data.remove(evicted.getKey()); } this.cap = newCapacity; } /** * Evicts the least recently used item from the cache. * * @return the evicted entry */ private Entry<K, V> evict() { if (head == null) { throw new RuntimeException("cache cannot be empty!"); } Entry<K, V> evicted = head; head = evicted.getNextEntry(); head.setPreEntry(null); evicted.setNextEntry(null); return evicted; } /** * Checks if the capacity is valid. * * @param capacity the capacity to check */ private void checkCapacity(int capacity) { if (capacity <= 0) { throw new RuntimeException("capacity must greater than 0!"); } } /** * Returns the value to which the specified key is mapped, or null if this cache contains no * mapping for the key. * * @param key the key whose associated value is to be returned * @return the value to which the specified key is mapped, or null if this cache contains no * mapping for the key */ public V get(K key) { if (!data.containsKey(key)) { return null; } final Entry<K, V> entry = data.get(key); moveNodeToLast(entry); return entry.getValue(); } /** * Moves the specified entry to the end of the list. * * @param entry the entry to move */ private void moveNodeToLast(Entry<K, V> entry) { if (tail == entry) { return; } final Entry<K, V> preEntry = entry.getPreEntry(); final Entry<K, V> nextEntry = entry.getNextEntry(); if (preEntry != null) { preEntry.setNextEntry(nextEntry); } if (nextEntry != null) { nextEntry.setPreEntry(preEntry); } if (head == entry) { head = nextEntry; } tail.setNextEntry(entry); entry.setPreEntry(tail); entry.setNextEntry(null); tail = entry; } /** * Associates the specified value with the specified key in this cache. * * @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) { if (data.containsKey(key)) { final Entry<K, V> existingEntry = data.get(key); existingEntry.setValue(value); moveNodeToLast(existingEntry); return; } Entry<K, V> newEntry; if (data.size() == cap) { newEntry = evict(); data.remove(newEntry.getKey()); } else { newEntry = new Entry<>(); } newEntry.setKey(key); newEntry.setValue(value); addNewEntry(newEntry); data.put(key, newEntry); } /** * Adds a new entry to the end of the list. * * @param newEntry the entry to add */ private void addNewEntry(Entry<K, V> newEntry) { if (data.isEmpty()) { head = newEntry; tail = newEntry; return; } tail.setNextEntry(newEntry); newEntry.setPreEntry(tail); newEntry.setNextEntry(null); tail = newEntry; } static final class Entry<I, J> { private Entry<I, J> preEntry; private Entry<I, J> nextEntry; private I key; private J value; Entry() { } Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; this.value = value; } public Entry<I, J> getPreEntry() { return preEntry; } public void setPreEntry(Entry<I, J> preEntry) { this.preEntry = preEntry; } public Entry<I, J> getNextEntry() { return nextEntry; } public void setNextEntry(Entry<I, J> nextEntry) { this.nextEntry = nextEntry; } public I getKey() { return key; } public void setKey(I key) { this.key = key; } public J getValue() { return value; } public void setValue(J value) { 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/caches/MRUCache.java
src/main/java/com/thealgorithms/datastructures/caches/MRUCache.java
package com.thealgorithms.datastructures.caches; import java.util.HashMap; import java.util.Map; /** * Represents a Most Recently Used (MRU) Cache. * <p> * In contrast to the Least Recently Used (LRU) strategy, the MRU caching policy * evicts the most recently accessed items first. This class provides methods to * store key-value pairs and manage cache eviction based on this policy. * * For more information, refer to: * <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#Most_recently_used_(MRU)">MRU on Wikipedia</a>. * * @param <K> the type of keys maintained by this cache * @param <V> the type of values associated with the keys */ public class MRUCache<K, V> { private final Map<K, Entry<K, V>> data = new HashMap<>(); private Entry<K, V> head; private Entry<K, V> tail; private int cap; private static final int DEFAULT_CAP = 100; /** * Creates an MRUCache with the default capacity. */ public MRUCache() { setCapacity(DEFAULT_CAP); } /** * Creates an MRUCache with a specified capacity. * * @param cap the maximum number of items the cache can hold */ public MRUCache(int cap) { setCapacity(cap); } /** * Sets the capacity of the cache and evicts items if the new capacity * is less than the current number of items. * * @param newCapacity the new capacity to set */ private void setCapacity(int newCapacity) { checkCapacity(newCapacity); while (data.size() > newCapacity) { Entry<K, V> evicted = evict(); data.remove(evicted.getKey()); } this.cap = newCapacity; } /** * Checks if the specified capacity is valid. * * @param capacity the capacity to check * @throws IllegalArgumentException if the capacity is less than or equal to zero */ private void checkCapacity(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity must be greater than 0!"); } } /** * Evicts the most recently used entry from the cache. * * @return the evicted entry * @throws RuntimeException if the cache is empty */ private Entry<K, V> evict() { if (head == null) { throw new RuntimeException("Cache cannot be empty!"); } final Entry<K, V> evicted = this.tail; tail = evicted.getPreEntry(); if (tail != null) { tail.setNextEntry(null); } evicted.setNextEntry(null); return evicted; } /** * Retrieves the value associated with the specified key. * * @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 get(K key) { if (!data.containsKey(key)) { return null; } final Entry<K, V> entry = data.get(key); moveEntryToLast(entry); return entry.getValue(); } /** * Associates the specified value with the specified key in the cache. * If the key already exists, its value is updated and the entry is moved to the most recently used position. * If the cache is full, the most recently used entry is evicted before adding the new entry. * * @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) { if (data.containsKey(key)) { final Entry<K, V> existingEntry = data.get(key); existingEntry.setValue(value); moveEntryToLast(existingEntry); return; } Entry<K, V> newEntry; if (data.size() == cap) { newEntry = evict(); data.remove(newEntry.getKey()); } else { newEntry = new Entry<>(); } newEntry.setKey(key); newEntry.setValue(value); addNewEntry(newEntry); data.put(key, newEntry); } /** * Adds a new entry to the cache and updates the head and tail pointers accordingly. * * @param newEntry the new entry to be added */ private void addNewEntry(Entry<K, V> newEntry) { if (data.isEmpty()) { head = newEntry; tail = newEntry; return; } tail.setNextEntry(newEntry); newEntry.setPreEntry(tail); newEntry.setNextEntry(null); tail = newEntry; } /** * Moves the specified entry to the most recently used position in the cache. * * @param entry the entry to be moved */ private void moveEntryToLast(Entry<K, V> entry) { if (tail == entry) { return; } final Entry<K, V> preEntry = entry.getPreEntry(); final Entry<K, V> nextEntry = entry.getNextEntry(); if (preEntry != null) { preEntry.setNextEntry(nextEntry); } if (nextEntry != null) { nextEntry.setPreEntry(preEntry); } if (head == entry) { head = nextEntry; } tail.setNextEntry(entry); entry.setPreEntry(tail); entry.setNextEntry(null); tail = entry; } /** * A nested class representing an entry in the cache, which holds a key-value pair * and references to the previous and next entries in the linked list structure. * * @param <I> the type of the key * @param <J> the type of the value */ static final class Entry<I, J> { private Entry<I, J> preEntry; private Entry<I, J> nextEntry; private I key; private J value; Entry() { } Entry(Entry<I, J> preEntry, Entry<I, J> nextEntry, I key, J value) { this.preEntry = preEntry; this.nextEntry = nextEntry; this.key = key; this.value = value; } public Entry<I, J> getPreEntry() { return preEntry; } public void setPreEntry(Entry<I, J> preEntry) { this.preEntry = preEntry; } public Entry<I, J> getNextEntry() { return nextEntry; } public void setNextEntry(Entry<I, J> nextEntry) { this.nextEntry = nextEntry; } public I getKey() { return key; } public void setKey(I key) { this.key = key; } public J getValue() { return value; } public void setValue(J value) { 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/caches/RRCache.java
src/main/java/com/thealgorithms/datastructures/caches/RRCache.java
package com.thealgorithms.datastructures.caches; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; /** * A thread-safe generic cache implementation using the Random Replacement (RR) eviction policy. * <p> * The cache holds a fixed number of entries, defined by its capacity. When the cache is full and a * new entry is added, one of the existing entries is selected at random and evicted to make space. * <p> * Optionally, entries can have a time-to-live (TTL) in milliseconds. If a TTL is set, entries will * automatically expire and be removed upon access or insertion attempts. * <p> * Features: * <ul> * <li>Random eviction when capacity is exceeded</li> * <li>Optional TTL (time-to-live in milliseconds) per entry or default TTL for all entries</li> * <li>Thread-safe access using locking</li> * <li>Hit and miss counters for cache statistics</li> * <li>Eviction listener callback support</li> * </ul> * * @param <K> the type of keys maintained by this cache * @param <V> the type of mapped values * See <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#Random_replacement_(RR)">Random Replacement</a> * @author Kevin Babu (<a href="https://www.github.com/KevinMwita7">GitHub</a>) */ public final class RRCache<K, V> { private final int capacity; private final long defaultTTL; private final Map<K, CacheEntry<V>> cache; private final List<K> keys; private final Random random; private final Lock lock; private long hits = 0; private long misses = 0; private final BiConsumer<K, V> evictionListener; private final EvictionStrategy<K, V> evictionStrategy; /** * Internal structure to store value + expiry timestamp. * * @param <V> the type of the value being cached */ private static class CacheEntry<V> { V value; long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). * * @param value the value to cache * @param ttlMillis the time-to-live in milliseconds */ CacheEntry(V value, long ttlMillis) { this.value = value; this.expiryTime = System.currentTimeMillis() + ttlMillis; } /** * Checks if the cache entry has expired. * * @return {@code true} if the current time is past the expiration time; {@code false} otherwise */ boolean isExpired() { return System.currentTimeMillis() > expiryTime; } } /** * Constructs a new {@code RRCache} instance using the provided {@link Builder}. * * <p>This constructor initializes the cache with the specified capacity and default TTL, * sets up internal data structures (a {@code HashMap} for cache entries and an {@code ArrayList} * for key tracking), and configures eviction and randomization behavior. * * @param builder the {@code Builder} object containing configuration parameters */ private RRCache(Builder<K, V> builder) { this.capacity = builder.capacity; this.defaultTTL = builder.defaultTTL; this.cache = new HashMap<>(builder.capacity); this.keys = new ArrayList<>(builder.capacity); this.random = builder.random != null ? builder.random : new Random(); this.lock = new ReentrantLock(); this.evictionListener = builder.evictionListener; this.evictionStrategy = builder.evictionStrategy; } /** * Retrieves the value associated with the specified key from the cache. * * <p>If the key is not present or the corresponding entry has expired, this method * returns {@code null}. If an expired entry is found, it will be removed and the * eviction listener (if any) will be notified. Cache hit-and-miss statistics are * also updated accordingly. * * @param key the key whose associated value is to be returned; must not be {@code null} * @return the cached value associated with the key, or {@code null} if not present or expired * @throws IllegalArgumentException if {@code key} is {@code null} */ public V get(K key) { if (key == null) { throw new IllegalArgumentException("Key must not be null"); } lock.lock(); try { evictionStrategy.onAccess(this); CacheEntry<V> entry = cache.get(key); if (entry == null || entry.isExpired()) { if (entry != null) { removeKey(key); notifyEviction(key, entry.value); } misses++; return null; } hits++; return entry.value; } finally { lock.unlock(); } } /** * Adds a key-value pair to the cache using the default time-to-live (TTL). * * <p>The key may overwrite an existing entry. The actual insertion is delegated * to the overloaded {@link #put(K, V, long)} method. * * @param key the key to cache the value under * @param value the value to be cached */ public void put(K key, V value) { put(key, value, defaultTTL); } /** * Adds a key-value pair to the cache with a specified time-to-live (TTL). * * <p>If the key already exists, its value is updated and its TTL is reset. If the key * does not exist and the cache is full, a random entry is evicted to make space. * Expired entries are also cleaned up prior to any eviction. The eviction listener * is notified when an entry gets evicted. * * @param key the key to associate with the cached value; must not be {@code null} * @param value the value to be cached; must not be {@code null} * @param ttlMillis the time-to-live for this entry in milliseconds; must be >= 0 * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null}, or if {@code ttlMillis} is negative */ public void put(K key, V value, long ttlMillis) { if (key == null || value == null) { throw new IllegalArgumentException("Key and value must not be null"); } if (ttlMillis < 0) { throw new IllegalArgumentException("TTL must be >= 0"); } lock.lock(); try { if (cache.containsKey(key)) { cache.put(key, new CacheEntry<>(value, ttlMillis)); return; } evictExpired(); if (cache.size() >= capacity) { int idx = random.nextInt(keys.size()); K evictKey = keys.remove(idx); CacheEntry<V> evictVal = cache.remove(evictKey); notifyEviction(evictKey, evictVal.value); } cache.put(key, new CacheEntry<>(value, ttlMillis)); keys.add(key); } finally { lock.unlock(); } } /** * Removes all expired entries from the cache. * * <p>This method iterates through the list of cached keys and checks each associated * entry for expiration. Expired entries are removed from both the key tracking list * and the cache map. For each eviction, the eviction listener is notified. */ private int evictExpired() { Iterator<K> it = keys.iterator(); int expiredCount = 0; while (it.hasNext()) { K k = it.next(); CacheEntry<V> entry = cache.get(k); if (entry != null && entry.isExpired()) { it.remove(); cache.remove(k); ++expiredCount; notifyEviction(k, entry.value); } } return expiredCount; } /** * Removes the specified key and its associated entry from the cache. * * <p>This method deletes the key from both the cache map and the key tracking list. * * @param key the key to remove from the cache */ private void removeKey(K key) { cache.remove(key); keys.remove(key); } /** * Notifies the eviction listener, if one is registered, that a key-value pair has been evicted. * * <p>If the {@code evictionListener} is not {@code null}, it is invoked with the provided key * and value. Any exceptions thrown by the listener are caught and logged to standard error, * preventing them from disrupting cache operations. * * @param key the key that was evicted * @param value the value that was associated with the evicted key */ private void notifyEviction(K key, V value) { if (evictionListener != null) { try { evictionListener.accept(key, value); } catch (Exception e) { System.err.println("Eviction listener failed: " + e.getMessage()); } } } /** * Returns the number of successful cache lookups (hits). * * @return the number of cache hits */ public long getHits() { lock.lock(); try { return hits; } finally { lock.unlock(); } } /** * Returns the number of failed cache lookups (misses), including expired entries. * * @return the number of cache misses */ public long getMisses() { lock.lock(); try { return misses; } finally { lock.unlock(); } } /** * Returns the current number of entries in the cache, excluding expired ones. * * @return the current cache size */ public int size() { lock.lock(); try { int cachedSize = cache.size(); int evictedCount = evictionStrategy.onAccess(this); if (evictedCount > 0) { return cachedSize - evictedCount; } // This runs if periodic eviction does not occur int count = 0; for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { ++count; } } return count; } finally { lock.unlock(); } } /** * Returns the current {@link EvictionStrategy} used by this cache instance. * @return the eviction strategy currently assigned to this cache */ public EvictionStrategy<K, V> getEvictionStrategy() { return evictionStrategy; } /** * Returns a string representation of the cache, including metadata and current non-expired entries. * * <p>The returned string includes the cache's capacity, current size (excluding expired entries), * hit-and-miss counts, and a map of all non-expired key-value pairs. This method acquires a lock * to ensure thread-safe access. * * @return a string summarizing the state of the cache */ @Override public String toString() { lock.lock(); try { Map<K, V> visible = new HashMap<>(); for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { visible.put(entry.getKey(), entry.getValue().value); } } return String.format("Cache(capacity=%d, size=%d, hits=%d, misses=%d, entries=%s)", capacity, visible.size(), hits, misses, visible); } finally { lock.unlock(); } } /** * A strategy interface for controlling when expired entries are evicted from the cache. * * <p>Implementations decide whether and when to trigger {@link RRCache#evictExpired()} based * on cache usage patterns. This allows for flexible eviction behaviour such as periodic cleanup, * or no automatic cleanup. * * @param <K> the type of keys maintained by the cache * @param <V> the type of cached values */ public interface EvictionStrategy<K, V> { /** * Called on each cache access (e.g., {@link RRCache#get(Object)}) to optionally trigger eviction. * * @param cache the cache instance on which this strategy is applied * @return the number of expired entries evicted during this access */ int onAccess(RRCache<K, V> cache); } /** * An eviction strategy that performs eviction of expired entries on each call. * * @param <K> the type of keys * @param <V> the type of values */ public static class NoEvictionStrategy<K, V> implements EvictionStrategy<K, V> { @Override public int onAccess(RRCache<K, V> cache) { return cache.evictExpired(); } } /** * An eviction strategy that triggers eviction every fixed number of accesses. * * <p>This deterministic strategy ensures cleanup occurs at predictable intervals, * ideal for moderately active caches where memory usage is a concern. * * @param <K> the type of keys * @param <V> the type of values */ public static class PeriodicEvictionStrategy<K, V> implements EvictionStrategy<K, V> { private final int interval; private int counter = 0; /** * Constructs a periodic eviction strategy. * * @param interval the number of accesses between evictions; must be > 0 * @throws IllegalArgumentException if {@code interval} is less than or equal to 0 */ public PeriodicEvictionStrategy(int interval) { if (interval <= 0) { throw new IllegalArgumentException("Interval must be > 0"); } this.interval = interval; } @Override public int onAccess(RRCache<K, V> cache) { if (++counter % interval == 0) { return cache.evictExpired(); } return 0; } } /** * A builder for constructing an {@link RRCache} instance with customizable settings. * * <p>Allows configuring capacity, default TTL, random eviction behavior, eviction listener, * and a pluggable eviction strategy. Call {@link #build()} to create the configured cache instance. * * @param <K> the type of keys maintained by the cache * @param <V> the type of values stored in the cache */ public static class Builder<K, V> { private final int capacity; private long defaultTTL = 0; private Random random; private BiConsumer<K, V> evictionListener; private EvictionStrategy<K, V> evictionStrategy = new RRCache.PeriodicEvictionStrategy<>(100); /** * Creates a new {@code Builder} with the specified cache capacity. * * @param capacity the maximum number of entries the cache can hold; must be > 0 * @throws IllegalArgumentException if {@code capacity} is less than or equal to 0 */ public Builder(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity must be > 0"); } this.capacity = capacity; } /** * Sets the default time-to-live (TTL) in milliseconds for cache entries. * * @param ttlMillis the TTL duration in milliseconds; must be >= 0 * @return this builder instance for chaining * @throws IllegalArgumentException if {@code ttlMillis} is negative */ public Builder<K, V> defaultTTL(long ttlMillis) { if (ttlMillis < 0) { throw new IllegalArgumentException("Default TTL must be >= 0"); } this.defaultTTL = ttlMillis; return this; } /** * Sets the {@link Random} instance to be used for random eviction selection. * * @param r a non-null {@code Random} instance * @return this builder instance for chaining * @throws IllegalArgumentException if {@code r} is {@code null} */ public Builder<K, V> random(Random r) { if (r == null) { throw new IllegalArgumentException("Random must not be null"); } this.random = r; return this; } /** * Sets an eviction listener to be notified when entries are evicted from the cache. * * @param listener a {@link BiConsumer} that accepts evicted keys and values; must not be {@code null} * @return this builder instance for chaining * @throws IllegalArgumentException if {@code listener} is {@code null} */ public Builder<K, V> evictionListener(BiConsumer<K, V> listener) { if (listener == null) { throw new IllegalArgumentException("Listener must not be null"); } this.evictionListener = listener; return this; } /** * Builds and returns a new {@link RRCache} instance with the configured parameters. * * @return a fully configured {@code RRCache} instance */ public RRCache<K, V> build() { return new RRCache<>(this); } /** * Sets the eviction strategy used to determine when to clean up expired entries. * * @param strategy an {@link EvictionStrategy} implementation; must not be {@code null} * @return this builder instance * @throws IllegalArgumentException if {@code strategy} is {@code null} */ public Builder<K, V> evictionStrategy(EvictionStrategy<K, V> strategy) { if (strategy == null) { throw new IllegalArgumentException("Eviction strategy must not be null"); } this.evictionStrategy = strategy; return this; } } }
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/caches/LIFOCache.java
src/main/java/com/thealgorithms/datastructures/caches/LIFOCache.java
package com.thealgorithms.datastructures.caches; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; /** * A thread-safe generic cache implementation using the Last-In-First-Out eviction policy. * <p> * The cache holds a fixed number of entries, defined by its capacity. When the cache is full and a * new entry is added, the youngest entry in the cache is selected and evicted to make space. * <p> * Optionally, entries can have a time-to-live (TTL) in milliseconds. If a TTL is set, entries will * automatically expire and be removed upon access or insertion attempts. * <p> * Features: * <ul> * <li>Removes youngest entry when capacity is exceeded</li> * <li>Optional TTL (time-to-live in milliseconds) per entry or default TTL for all entries</li> * <li>Thread-safe access using locking</li> * <li>Hit and miss counters for cache statistics</li> * <li>Eviction listener callback support</li> * </ul> * * @param <K> the type of keys maintained by this cache * @param <V> the type of mapped values * See <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#Last_in_first_out_(LIFO)_or_First_in_last_out_(FILO)">LIFO</a> * @author Kevin Babu (<a href="https://www.github.com/KevinMwita7">GitHub</a>) */ public final class LIFOCache<K, V> { private final int capacity; private final long defaultTTL; private final Map<K, CacheEntry<V>> cache; private final Lock lock; private final Deque<K> keys; private long hits = 0; private long misses = 0; private final BiConsumer<K, V> evictionListener; private final EvictionStrategy<K, V> evictionStrategy; /** * Internal structure to store value + expiry timestamp. * * @param <V> the type of the value being cached */ private static class CacheEntry<V> { V value; long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). * If TTL is 0, the entry is kept indefinitely, that is, unless it is the first value, * then it will be removed according to the LIFO principle * * @param value the value to cache * @param ttlMillis the time-to-live in milliseconds */ CacheEntry(V value, long ttlMillis) { this.value = value; if (ttlMillis == 0) { this.expiryTime = Long.MAX_VALUE; } else { this.expiryTime = System.currentTimeMillis() + ttlMillis; } } /** * Checks if the cache entry has expired. * * @return {@code true} if the current time is past the expiration time; {@code false} otherwise */ boolean isExpired() { return System.currentTimeMillis() > expiryTime; } } /** * Constructs a new {@code LIFOCache} instance using the provided {@link Builder}. * * <p>This constructor initializes the cache with the specified capacity and default TTL, * sets up internal data structures (a {@code HashMap} for cache entries, * {an @code ArrayDeque}, for key storage, and configures eviction. * * @param builder the {@code Builder} object containing configuration parameters */ private LIFOCache(Builder<K, V> builder) { this.capacity = builder.capacity; this.defaultTTL = builder.defaultTTL; this.cache = new HashMap<>(builder.capacity); this.keys = new ArrayDeque<>(builder.capacity); this.lock = new ReentrantLock(); this.evictionListener = builder.evictionListener; this.evictionStrategy = builder.evictionStrategy; } /** * Retrieves the value associated with the specified key from the cache. * * <p>If the key is not present or the corresponding entry has expired, this method * returns {@code null}. If an expired entry is found, it will be removed and the * eviction listener (if any) will be notified. Cache hit-and-miss statistics are * also updated accordingly. * * @param key the key whose associated value is to be returned; must not be {@code null} * @return the cached value associated with the key, or {@code null} if not present or expired * @throws IllegalArgumentException if {@code key} is {@code null} */ public V get(K key) { if (key == null) { throw new IllegalArgumentException("Key must not be null"); } lock.lock(); try { evictionStrategy.onAccess(this); final CacheEntry<V> entry = cache.get(key); if (entry == null || entry.isExpired()) { if (entry != null) { cache.remove(key); keys.remove(key); notifyEviction(key, entry.value); } misses++; return null; } hits++; return entry.value; } finally { lock.unlock(); } } /** * Adds a key-value pair to the cache using the default time-to-live (TTL). * * <p>The key may overwrite an existing entry. The actual insertion is delegated * to the overloaded {@link #put(K, V, long)} method. * * @param key the key to cache the value under * @param value the value to be cached */ public void put(K key, V value) { put(key, value, defaultTTL); } /** * Adds a key-value pair to the cache with a specified time-to-live (TTL). * * <p>If the key already exists, its value is removed, re-inserted at tail and its TTL is reset. * If the key does not exist and the cache is full, the youngest entry is evicted to make space. * Expired entries are also cleaned up prior to any eviction. The eviction listener * is notified when an entry gets evicted. * * @param key the key to associate with the cached value; must not be {@code null} * @param value the value to be cached; must not be {@code null} * @param ttlMillis the time-to-live for this entry in milliseconds; must be >= 0 * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null}, or if {@code ttlMillis} is negative */ public void put(K key, V value, long ttlMillis) { if (key == null || value == null) { throw new IllegalArgumentException("Key and value must not be null"); } if (ttlMillis < 0) { throw new IllegalArgumentException("TTL must be >= 0"); } lock.lock(); try { // If key already exists, remove it. It will later be re-inserted at top of stack keys.remove(key); final CacheEntry<V> oldEntry = cache.remove(key); if (oldEntry != null && !oldEntry.isExpired()) { notifyEviction(key, oldEntry.value); } // Evict expired entries to make space for new entry evictExpired(); // If no expired entry was removed, remove the youngest if (cache.size() >= capacity) { final K youngestKey = keys.pollLast(); final CacheEntry<V> youngestEntry = cache.remove(youngestKey); notifyEviction(youngestKey, youngestEntry.value); } // Insert new entry at tail keys.add(key); cache.put(key, new CacheEntry<>(value, ttlMillis)); } finally { lock.unlock(); } } /** * Removes all expired entries from the cache. * * <p>This method iterates through the list of cached keys and checks each associated * entry for expiration. Expired entries are removed the cache map. For each eviction, * the eviction listener is notified. */ private int evictExpired() { int count = 0; final Iterator<K> it = keys.iterator(); while (it.hasNext()) { final K k = it.next(); final CacheEntry<V> entry = cache.get(k); if (entry != null && entry.isExpired()) { it.remove(); cache.remove(k); notifyEviction(k, entry.value); count++; } } return count; } /** * Removes the specified key and its associated entry from the cache. * * @param key the key to remove from the cache; * @return the value associated with the key; or {@code null} if no such key exists */ public V removeKey(K key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } lock.lock(); try { final CacheEntry<V> entry = cache.remove(key); keys.remove(key); // No such key in cache if (entry == null) { return null; } notifyEviction(key, entry.value); return entry.value; } finally { lock.unlock(); } } /** * Notifies the eviction listener, if one is registered, that a key-value pair has been evicted. * * <p>If the {@code evictionListener} is not {@code null}, it is invoked with the provided key * and value. Any exceptions thrown by the listener are caught and logged to standard error, * preventing them from disrupting cache operations. * * @param key the key that was evicted * @param value the value that was associated with the evicted key */ private void notifyEviction(K key, V value) { if (evictionListener != null) { try { evictionListener.accept(key, value); } catch (Exception e) { System.err.println("Eviction listener failed: " + e.getMessage()); } } } /** * Returns the number of successful cache lookups (hits). * * @return the number of cache hits */ public long getHits() { lock.lock(); try { return hits; } finally { lock.unlock(); } } /** * Returns the number of failed cache lookups (misses), including expired entries. * * @return the number of cache misses */ public long getMisses() { lock.lock(); try { return misses; } finally { lock.unlock(); } } /** * Returns the current number of entries in the cache, excluding expired ones. * * @return the current cache size */ public int size() { lock.lock(); try { evictionStrategy.onAccess(this); int count = 0; for (CacheEntry<V> entry : cache.values()) { if (!entry.isExpired()) { ++count; } } return count; } finally { lock.unlock(); } } /** * Removes all entries from the cache, regardless of their expiration status. * * <p>This method clears the internal cache map entirely, resets the hit-and-miss counters, * and notifies the eviction listener (if any) for each removed entry. * Note that expired entries are treated the same as active ones for the purpose of clearing. * * <p>This operation acquires the internal lock to ensure thread safety. */ public void clear() { lock.lock(); try { for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { notifyEviction(entry.getKey(), entry.getValue().value); } keys.clear(); cache.clear(); hits = 0; misses = 0; } finally { lock.unlock(); } } /** * Returns a set of all keys currently stored in the cache that have not expired. * * <p>This method iterates through the cache and collects the keys of all non-expired entries. * Expired entries are ignored but not removed. If you want to ensure expired entries are cleaned up, * consider invoking {@link EvictionStrategy#onAccess(LIFOCache)} or calling {@link #evictExpired()} manually. * * <p>This operation acquires the internal lock to ensure thread safety. * * @return a set containing all non-expired keys currently in the cache */ public Set<K> getAllKeys() { lock.lock(); try { final Set<K> result = new HashSet<>(); for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { result.add(entry.getKey()); } } return result; } finally { lock.unlock(); } } /** * Returns the current {@link EvictionStrategy} used by this cache instance. * @return the eviction strategy currently assigned to this cache */ public EvictionStrategy<K, V> getEvictionStrategy() { return evictionStrategy; } /** * Returns a string representation of the cache, including metadata and current non-expired entries. * * <p>The returned string includes the cache's capacity, current size (excluding expired entries), * hit-and-miss counts, and a map of all non-expired key-value pairs. This method acquires a lock * to ensure thread-safe access. * * @return a string summarizing the state of the cache */ @Override public String toString() { lock.lock(); try { final Map<K, V> visible = new LinkedHashMap<>(); for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { visible.put(entry.getKey(), entry.getValue().value); } } return String.format("Cache(capacity=%d, size=%d, hits=%d, misses=%d, entries=%s)", capacity, visible.size(), hits, misses, visible); } finally { lock.unlock(); } } /** * A strategy interface for controlling when expired entries are evicted from the cache. * * <p>Implementations decide whether and when to trigger {@link LIFOCache#evictExpired()} based * on cache usage patterns. This allows for flexible eviction behaviour such as periodic cleanup, * or no automatic cleanup. * * @param <K> the type of keys maintained by the cache * @param <V> the type of cached values */ public interface EvictionStrategy<K, V> { /** * Called on each cache access (e.g., {@link LIFOCache#get(Object)}) to optionally trigger eviction. * * @param cache the cache instance on which this strategy is applied * @return the number of expired entries evicted during this access */ int onAccess(LIFOCache<K, V> cache); } /** * An eviction strategy that performs eviction of expired entries on each call. * * @param <K> the type of keys * @param <V> the type of values */ public static class ImmediateEvictionStrategy<K, V> implements EvictionStrategy<K, V> { @Override public int onAccess(LIFOCache<K, V> cache) { return cache.evictExpired(); } } /** * An eviction strategy that triggers eviction on every fixed number of accesses. * * <p>This deterministic strategy ensures cleanup occurs at predictable intervals, * ideal for moderately active caches where memory usage is a concern. * * @param <K> the type of keys * @param <V> the type of values */ public static class PeriodicEvictionStrategy<K, V> implements EvictionStrategy<K, V> { private final int interval; private final AtomicInteger counter = new AtomicInteger(); /** * Constructs a periodic eviction strategy. * * @param interval the number of accesses between evictions; must be > 0 * @throws IllegalArgumentException if {@code interval} is less than or equal to 0 */ public PeriodicEvictionStrategy(int interval) { if (interval <= 0) { throw new IllegalArgumentException("Interval must be > 0"); } this.interval = interval; } @Override public int onAccess(LIFOCache<K, V> cache) { if (counter.incrementAndGet() % interval == 0) { return cache.evictExpired(); } return 0; } } /** * A builder for constructing a {@link LIFOCache} instance with customizable settings. * * <p>Allows configuring capacity, default TTL, eviction listener, and a pluggable eviction * strategy. Call {@link #build()} to create the configured cache instance. * * @param <K> the type of keys maintained by the cache * @param <V> the type of values stored in the cache */ public static class Builder<K, V> { private final int capacity; private long defaultTTL = 0; private BiConsumer<K, V> evictionListener; private EvictionStrategy<K, V> evictionStrategy = new LIFOCache.ImmediateEvictionStrategy<>(); /** * Creates a new {@code Builder} with the specified cache capacity. * * @param capacity the maximum number of entries the cache can hold; must be > 0 * @throws IllegalArgumentException if {@code capacity} is less than or equal to 0 */ public Builder(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity must be > 0"); } this.capacity = capacity; } /** * Sets the default time-to-live (TTL) in milliseconds for cache entries. * * @param ttlMillis the TTL duration in milliseconds; must be >= 0 * @return this builder instance for chaining * @throws IllegalArgumentException if {@code ttlMillis} is negative */ public Builder<K, V> defaultTTL(long ttlMillis) { if (ttlMillis < 0) { throw new IllegalArgumentException("Default TTL must be >= 0"); } this.defaultTTL = ttlMillis; return this; } /** * Sets an eviction listener to be notified when entries are evicted from the cache. * * @param listener a {@link BiConsumer} that accepts evicted keys and values; must not be {@code null} * @return this builder instance for chaining * @throws IllegalArgumentException if {@code listener} is {@code null} */ public Builder<K, V> evictionListener(BiConsumer<K, V> listener) { if (listener == null) { throw new IllegalArgumentException("Listener must not be null"); } this.evictionListener = listener; return this; } /** * Builds and returns a new {@link LIFOCache} instance with the configured parameters. * * @return a fully configured {@code LIFOCache} instance */ public LIFOCache<K, V> build() { return new LIFOCache<>(this); } /** * Sets the eviction strategy used to determine when to clean up expired entries. * * @param strategy an {@link EvictionStrategy} implementation; must not be {@code null} * @return this builder instance * @throws IllegalArgumentException if {@code strategy} is {@code null} */ public Builder<K, V> evictionStrategy(EvictionStrategy<K, V> strategy) { if (strategy == null) { throw new IllegalArgumentException("Eviction strategy must not be null"); } this.evictionStrategy = strategy; return this; } } }
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/caches/FIFOCache.java
src/main/java/com/thealgorithms/datastructures/caches/FIFOCache.java
package com.thealgorithms.datastructures.caches; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiConsumer; /** * A thread-safe generic cache implementation using the First-In-First-Out eviction policy. * <p> * The cache holds a fixed number of entries, defined by its capacity. When the cache is full and a * new entry is added, the oldest entry in the cache is selected and evicted to make space. * <p> * Optionally, entries can have a time-to-live (TTL) in milliseconds. If a TTL is set, entries will * automatically expire and be removed upon access or insertion attempts. * <p> * Features: * <ul> * <li>Removes oldest entry when capacity is exceeded</li> * <li>Optional TTL (time-to-live in milliseconds) per entry or default TTL for all entries</li> * <li>Thread-safe access using locking</li> * <li>Hit and miss counters for cache statistics</li> * <li>Eviction listener callback support</li> * </ul> * * @param <K> the type of keys maintained by this cache * @param <V> the type of mapped values * See <a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#First_in_first_out_(FIFO)">FIFO</a> * @author Kevin Babu (<a href="https://www.github.com/KevinMwita7">GitHub</a>) */ public final class FIFOCache<K, V> { private final int capacity; private final long defaultTTL; private final Map<K, CacheEntry<V>> cache; private final Lock lock; private long hits = 0; private long misses = 0; private final BiConsumer<K, V> evictionListener; private final EvictionStrategy<K, V> evictionStrategy; /** * Internal structure to store value + expiry timestamp. * * @param <V> the type of the value being cached */ private static class CacheEntry<V> { V value; long expiryTime; /** * Constructs a new {@code CacheEntry} with the specified value and time-to-live (TTL). * If TTL is 0, the entry is kept indefinitely, that is, unless it is the first value, * then it will be removed according to the FIFO principle * * @param value the value to cache * @param ttlMillis the time-to-live in milliseconds */ CacheEntry(V value, long ttlMillis) { this.value = value; if (ttlMillis == 0) { this.expiryTime = Long.MAX_VALUE; } else { this.expiryTime = System.currentTimeMillis() + ttlMillis; } } /** * Checks if the cache entry has expired. * * @return {@code true} if the current time is past the expiration time; {@code false} otherwise */ boolean isExpired() { return System.currentTimeMillis() > expiryTime; } } /** * Constructs a new {@code FIFOCache} instance using the provided {@link Builder}. * * <p>This constructor initializes the cache with the specified capacity and default TTL, * sets up internal data structures (a {@code LinkedHashMap} for cache entries and configures eviction. * * @param builder the {@code Builder} object containing configuration parameters */ private FIFOCache(Builder<K, V> builder) { this.capacity = builder.capacity; this.defaultTTL = builder.defaultTTL; this.cache = new LinkedHashMap<>(); this.lock = new ReentrantLock(); this.evictionListener = builder.evictionListener; this.evictionStrategy = builder.evictionStrategy; } /** * Retrieves the value associated with the specified key from the cache. * * <p>If the key is not present or the corresponding entry has expired, this method * returns {@code null}. If an expired entry is found, it will be removed and the * eviction listener (if any) will be notified. Cache hit-and-miss statistics are * also updated accordingly. * * @param key the key whose associated value is to be returned; must not be {@code null} * @return the cached value associated with the key, or {@code null} if not present or expired * @throws IllegalArgumentException if {@code key} is {@code null} */ public V get(K key) { if (key == null) { throw new IllegalArgumentException("Key must not be null"); } lock.lock(); try { evictionStrategy.onAccess(this); CacheEntry<V> entry = cache.get(key); if (entry == null || entry.isExpired()) { if (entry != null) { cache.remove(key); notifyEviction(key, entry.value); } misses++; return null; } hits++; return entry.value; } finally { lock.unlock(); } } /** * Adds a key-value pair to the cache using the default time-to-live (TTL). * * <p>The key may overwrite an existing entry. The actual insertion is delegated * to the overloaded {@link #put(K, V, long)} method. * * @param key the key to cache the value under * @param value the value to be cached */ public void put(K key, V value) { put(key, value, defaultTTL); } /** * Adds a key-value pair to the cache with a specified time-to-live (TTL). * * <p>If the key already exists, its value is removed, re-inserted at tail and its TTL is reset. * If the key does not exist and the cache is full, the oldest entry is evicted to make space. * Expired entries are also cleaned up prior to any eviction. The eviction listener * is notified when an entry gets evicted. * * @param key the key to associate with the cached value; must not be {@code null} * @param value the value to be cached; must not be {@code null} * @param ttlMillis the time-to-live for this entry in milliseconds; must be >= 0 * @throws IllegalArgumentException if {@code key} or {@code value} is {@code null}, or if {@code ttlMillis} is negative */ public void put(K key, V value, long ttlMillis) { if (key == null || value == null) { throw new IllegalArgumentException("Key and value must not be null"); } if (ttlMillis < 0) { throw new IllegalArgumentException("TTL must be >= 0"); } lock.lock(); try { // If key already exists, remove it CacheEntry<V> oldEntry = cache.remove(key); if (oldEntry != null && !oldEntry.isExpired()) { notifyEviction(key, oldEntry.value); } // Evict expired entries to make space for new entry evictExpired(); // If no expired entry was removed, remove the oldest if (cache.size() >= capacity) { Iterator<Map.Entry<K, CacheEntry<V>>> it = cache.entrySet().iterator(); if (it.hasNext()) { Map.Entry<K, CacheEntry<V>> eldest = it.next(); it.remove(); notifyEviction(eldest.getKey(), eldest.getValue().value); } } // Insert new entry at tail cache.put(key, new CacheEntry<>(value, ttlMillis)); } finally { lock.unlock(); } } /** * Removes all expired entries from the cache. * * <p>This method iterates through the list of cached keys and checks each associated * entry for expiration. Expired entries are removed the cache map. For each eviction, * the eviction listener is notified. */ private int evictExpired() { int count = 0; Iterator<Map.Entry<K, CacheEntry<V>>> it = cache.entrySet().iterator(); while (it.hasNext()) { Map.Entry<K, CacheEntry<V>> entry = it.next(); if (entry != null && entry.getValue().isExpired()) { it.remove(); notifyEviction(entry.getKey(), entry.getValue().value); count++; } } return count; } /** * Removes the specified key and its associated entry from the cache. * * @param key the key to remove from the cache; * @return the value associated with the key; or {@code null} if no such key exists */ public V removeKey(K key) { if (key == null) { throw new IllegalArgumentException("Key cannot be null"); } CacheEntry<V> entry = cache.remove(key); // No such key in cache if (entry == null) { return null; } notifyEviction(key, entry.value); return entry.value; } /** * Notifies the eviction listener, if one is registered, that a key-value pair has been evicted. * * <p>If the {@code evictionListener} is not {@code null}, it is invoked with the provided key * and value. Any exceptions thrown by the listener are caught and logged to standard error, * preventing them from disrupting cache operations. * * @param key the key that was evicted * @param value the value that was associated with the evicted key */ private void notifyEviction(K key, V value) { if (evictionListener != null) { try { evictionListener.accept(key, value); } catch (Exception e) { System.err.println("Eviction listener failed: " + e.getMessage()); } } } /** * Returns the number of successful cache lookups (hits). * * @return the number of cache hits */ public long getHits() { lock.lock(); try { return hits; } finally { lock.unlock(); } } /** * Returns the number of failed cache lookups (misses), including expired entries. * * @return the number of cache misses */ public long getMisses() { lock.lock(); try { return misses; } finally { lock.unlock(); } } /** * Returns the current number of entries in the cache, excluding expired ones. * * @return the current cache size */ public int size() { lock.lock(); try { evictionStrategy.onAccess(this); int count = 0; for (CacheEntry<V> entry : cache.values()) { if (!entry.isExpired()) { ++count; } } return count; } finally { lock.unlock(); } } /** * Removes all entries from the cache, regardless of their expiration status. * * <p>This method clears the internal cache map entirely, resets the hit-and-miss counters, * and notifies the eviction listener (if any) for each removed entry. * Note that expired entries are treated the same as active ones for the purpose of clearing. * * <p>This operation acquires the internal lock to ensure thread safety. */ public void clear() { lock.lock(); try { for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { notifyEviction(entry.getKey(), entry.getValue().value); } cache.clear(); hits = 0; misses = 0; } finally { lock.unlock(); } } /** * Returns a set of all keys currently stored in the cache that have not expired. * * <p>This method iterates through the cache and collects the keys of all non-expired entries. * Expired entries are ignored but not removed. If you want to ensure expired entries are cleaned up, * consider invoking {@link EvictionStrategy#onAccess(FIFOCache)} or calling {@link #evictExpired()} manually. * * <p>This operation acquires the internal lock to ensure thread safety. * * @return a set containing all non-expired keys currently in the cache */ public Set<K> getAllKeys() { lock.lock(); try { Set<K> keys = new LinkedHashSet<>(); for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { keys.add(entry.getKey()); } } return keys; } finally { lock.unlock(); } } /** * Returns the current {@link EvictionStrategy} used by this cache instance. * @return the eviction strategy currently assigned to this cache */ public EvictionStrategy<K, V> getEvictionStrategy() { return evictionStrategy; } /** * Returns a string representation of the cache, including metadata and current non-expired entries. * * <p>The returned string includes the cache's capacity, current size (excluding expired entries), * hit-and-miss counts, and a map of all non-expired key-value pairs. This method acquires a lock * to ensure thread-safe access. * * @return a string summarizing the state of the cache */ @Override public String toString() { lock.lock(); try { Map<K, V> visible = new LinkedHashMap<>(); for (Map.Entry<K, CacheEntry<V>> entry : cache.entrySet()) { if (!entry.getValue().isExpired()) { visible.put(entry.getKey(), entry.getValue().value); } } return String.format("Cache(capacity=%d, size=%d, hits=%d, misses=%d, entries=%s)", capacity, visible.size(), hits, misses, visible); } finally { lock.unlock(); } } /** * A strategy interface for controlling when expired entries are evicted from the cache. * * <p>Implementations decide whether and when to trigger {@link FIFOCache#evictExpired()} based * on cache usage patterns. This allows for flexible eviction behaviour such as periodic cleanup, * or no automatic cleanup. * * @param <K> the type of keys maintained by the cache * @param <V> the type of cached values */ public interface EvictionStrategy<K, V> { /** * Called on each cache access (e.g., {@link FIFOCache#get(Object)}) to optionally trigger eviction. * * @param cache the cache instance on which this strategy is applied * @return the number of expired entries evicted during this access */ int onAccess(FIFOCache<K, V> cache); } /** * An eviction strategy that performs eviction of expired entries on each call. * * @param <K> the type of keys * @param <V> the type of values */ public static class ImmediateEvictionStrategy<K, V> implements EvictionStrategy<K, V> { @Override public int onAccess(FIFOCache<K, V> cache) { return cache.evictExpired(); } } /** * An eviction strategy that triggers eviction on every fixed number of accesses. * * <p>This deterministic strategy ensures cleanup occurs at predictable intervals, * ideal for moderately active caches where memory usage is a concern. * * @param <K> the type of keys * @param <V> the type of values */ public static class PeriodicEvictionStrategy<K, V> implements EvictionStrategy<K, V> { private final int interval; private final AtomicInteger counter = new AtomicInteger(); /** * Constructs a periodic eviction strategy. * * @param interval the number of accesses between evictions; must be > 0 * @throws IllegalArgumentException if {@code interval} is less than or equal to 0 */ public PeriodicEvictionStrategy(int interval) { if (interval <= 0) { throw new IllegalArgumentException("Interval must be > 0"); } this.interval = interval; } @Override public int onAccess(FIFOCache<K, V> cache) { if (counter.incrementAndGet() % interval == 0) { return cache.evictExpired(); } return 0; } } /** * A builder for constructing a {@link FIFOCache} instance with customizable settings. * * <p>Allows configuring capacity, default TTL, eviction listener, and a pluggable eviction * strategy. Call {@link #build()} to create the configured cache instance. * * @param <K> the type of keys maintained by the cache * @param <V> the type of values stored in the cache */ public static class Builder<K, V> { private final int capacity; private long defaultTTL = 0; private BiConsumer<K, V> evictionListener; private EvictionStrategy<K, V> evictionStrategy = new FIFOCache.ImmediateEvictionStrategy<>(); /** * Creates a new {@code Builder} with the specified cache capacity. * * @param capacity the maximum number of entries the cache can hold; must be > 0 * @throws IllegalArgumentException if {@code capacity} is less than or equal to 0 */ public Builder(int capacity) { if (capacity <= 0) { throw new IllegalArgumentException("Capacity must be > 0"); } this.capacity = capacity; } /** * Sets the default time-to-live (TTL) in milliseconds for cache entries. * * @param ttlMillis the TTL duration in milliseconds; must be >= 0 * @return this builder instance for chaining * @throws IllegalArgumentException if {@code ttlMillis} is negative */ public Builder<K, V> defaultTTL(long ttlMillis) { if (ttlMillis < 0) { throw new IllegalArgumentException("Default TTL must be >= 0"); } this.defaultTTL = ttlMillis; return this; } /** * Sets an eviction listener to be notified when entries are evicted from the cache. * * @param listener a {@link BiConsumer} that accepts evicted keys and values; must not be {@code null} * @return this builder instance for chaining * @throws IllegalArgumentException if {@code listener} is {@code null} */ public Builder<K, V> evictionListener(BiConsumer<K, V> listener) { if (listener == null) { throw new IllegalArgumentException("Listener must not be null"); } this.evictionListener = listener; return this; } /** * Builds and returns a new {@link FIFOCache} instance with the configured parameters. * * @return a fully configured {@code FIFOCache} instance */ public FIFOCache<K, V> build() { return new FIFOCache<>(this); } /** * Sets the eviction strategy used to determine when to clean up expired entries. * * @param strategy an {@link EvictionStrategy} implementation; must not be {@code null} * @return this builder instance * @throws IllegalArgumentException if {@code strategy} is {@code null} */ public Builder<K, V> evictionStrategy(EvictionStrategy<K, V> strategy) { if (strategy == null) { throw new IllegalArgumentException("Eviction strategy must not be null"); } this.evictionStrategy = strategy; return this; } } }
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/bloomfilter/BloomFilter.java
src/main/java/com/thealgorithms/datastructures/bloomfilter/BloomFilter.java
package com.thealgorithms.datastructures.bloomfilter; import java.util.Arrays; import java.util.BitSet; /** * A generic BloomFilter implementation for probabilistic membership checking. * <p> * Bloom filters are space-efficient data structures that provide a fast way to * test whether an * element is a member of a set. They may produce false positives, indicating an * element is * in the set when it is not, but they will never produce false negatives. * </p> * * @param <T> The type of elements to be stored in the Bloom filter. */ @SuppressWarnings("rawtypes") public class BloomFilter<T> { private final int numberOfHashFunctions; private final BitSet bitArray; private final Hash<T>[] hashFunctions; /** * Constructs a BloomFilter with a specified number of hash functions and bit * array size. * * @param numberOfHashFunctions the number of hash functions to use * @param bitArraySize the size of the bit array, which determines the * capacity of the filter * @throws IllegalArgumentException if numberOfHashFunctions or bitArraySize is * less than 1 */ @SuppressWarnings("unchecked") public BloomFilter(int numberOfHashFunctions, int bitArraySize) { if (numberOfHashFunctions < 1 || bitArraySize < 1) { throw new IllegalArgumentException("Number of hash functions and bit array size must be greater than 0"); } this.numberOfHashFunctions = numberOfHashFunctions; this.bitArray = new BitSet(bitArraySize); this.hashFunctions = new Hash[numberOfHashFunctions]; initializeHashFunctions(); } /** * Initializes the hash functions with unique indices to ensure different * hashing. */ private void initializeHashFunctions() { for (int i = 0; i < numberOfHashFunctions; i++) { hashFunctions[i] = new Hash<>(i); } } /** * Inserts an element into the Bloom filter. * <p> * This method hashes the element using all defined hash functions and sets the * corresponding * bits in the bit array. * </p> * * @param key the element to insert into the Bloom filter */ public void insert(T key) { for (Hash<T> hash : hashFunctions) { int position = Math.abs(hash.compute(key) % bitArray.size()); bitArray.set(position); } } /** * Checks if an element might be in the Bloom filter. * <p> * This method checks the bits at the positions computed by each hash function. * If any of these * bits are not set, the element is definitely not in the filter. If all bits * are set, the element * might be in the filter. * </p> * * @param key the element to check for membership in the Bloom filter * @return {@code true} if the element might be in the Bloom filter, * {@code false} if it is definitely not */ public boolean contains(T key) { for (Hash<T> hash : hashFunctions) { int position = Math.abs(hash.compute(key) % bitArray.size()); if (!bitArray.get(position)) { return false; } } return true; } /** * Inner class representing a hash function used by the Bloom filter. * <p> * Each instance of this class represents a different hash function based on its * index. * </p> * * @param <T> The type of elements to be hashed. */ private static class Hash<T> { private final int index; /** * Constructs a Hash function with a specified index. * * @param index the index of this hash function, used to create a unique hash */ Hash(int index) { this.index = index; } /** * Computes the hash of the given key. * <p> * The hash value is calculated by multiplying the index of the hash function * with the ASCII sum of the string representation of the key. * </p> * * @param key the element to hash * @return the computed hash value */ public int compute(T key) { return index * contentHash(key); } /** * Computes the ASCII value sum of the characters in a string. * <p> * This method iterates through each character of the string and accumulates * their ASCII values to produce a single integer value. * </p> * * @param word the string to compute * @return the sum of ASCII values of the characters in the string */ private int asciiString(String word) { int sum = 0; for (char c : word.toCharArray()) { sum += c; } return sum; } /** * Computes a content-based hash for arrays; falls back to ASCII-sum of String value otherwise. */ private int contentHash(Object key) { if (key instanceof int[]) { return Arrays.hashCode((int[]) key); } else if (key instanceof long[]) { return Arrays.hashCode((long[]) key); } else if (key instanceof byte[]) { return Arrays.hashCode((byte[]) key); } else if (key instanceof short[]) { return Arrays.hashCode((short[]) key); } else if (key instanceof char[]) { return Arrays.hashCode((char[]) key); } else if (key instanceof boolean[]) { return Arrays.hashCode((boolean[]) key); } else if (key instanceof float[]) { return Arrays.hashCode((float[]) key); } else if (key instanceof double[]) { return Arrays.hashCode((double[]) key); } else if (key instanceof Object[]) { return Arrays.deepHashCode((Object[]) key); } return asciiString(String.valueOf(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/trees/CheckIfBinaryTreeBalanced.java
src/main/java/com/thealgorithms/datastructures/trees/CheckIfBinaryTreeBalanced.java
package com.thealgorithms.datastructures.trees; import java.util.HashMap; import java.util.Stack; /** * This class will check if a BinaryTree is balanced. A balanced binary tree is * defined as a binary tree where the difference in height between the left and * right subtree of each node differs by at most one. * <p> * This can be done in both an iterative and recursive fashion. Below, * `isBalancedRecursive()` is implemented in a recursive fashion, and * `isBalancedIterative()` is implemented in an iterative fashion. * * @author [Ian Cowan](<a href="https://github.com/iccowan">Git-Ian Cowan</a>) */ public final class CheckIfBinaryTreeBalanced { private CheckIfBinaryTreeBalanced() { } /** * Recursive is BT balanced implementation * * @param root The binary tree to check if balanced */ public static boolean isBalancedRecursive(BinaryTree.Node root) { if (root == null) { return true; } // Create an array of length 1 to keep track of our balance // Default to true. We use an array, so we have an efficient mutable object boolean[] isBalanced = new boolean[1]; isBalanced[0] = true; // Check for balance and return whether we are balanced isBalancedRecursive(root, 0, isBalanced); return isBalanced[0]; } /** * Private helper method to keep track of the depth and balance during * recursion. We effectively perform a modified post-order traversal where * we are looking at the heights of both children of each node in the tree * * @param node The current node to explore * @param depth The current depth of the node * @param isBalanced The array of length 1 keeping track of our balance */ private static int isBalancedRecursive(BinaryTree.Node node, int depth, boolean[] isBalanced) { // If the node is null, we should not explore it and the height is 0 // If the tree is already not balanced, might as well stop because we // can't make it balanced now! if (node == null || !isBalanced[0]) { return 0; } // Visit the left and right children, incrementing their depths by 1 int leftHeight = isBalancedRecursive(node.left, depth + 1, isBalanced); int rightHeight = isBalancedRecursive(node.right, depth + 1, isBalanced); // If the height of either of the left or right subtrees differ by more // than 1, we cannot be balanced if (Math.abs(leftHeight - rightHeight) > 1) { isBalanced[0] = false; } // The height of our tree is the maximum of the heights of the left // and right subtrees plus one return Math.max(leftHeight, rightHeight) + 1; } /** * Iterative is BT balanced implementation */ public static boolean isBalancedIterative(BinaryTree.Node root) { if (root == null) { return true; } // Default that we are balanced and our algo will prove it wrong boolean isBalanced = true; // Create a stack for our post order traversal Stack<BinaryTree.Node> nodeStack = new Stack<>(); // For post order traversal, we'll have to keep track of where we // visited last BinaryTree.Node lastVisited = null; // Create a HashMap to keep track of the subtree heights for each node HashMap<BinaryTree.Node, Integer> subtreeHeights = new HashMap<>(); // We begin at the root of the tree BinaryTree.Node node = root; // We loop while: // - the node stack is empty and the node we explore is null // AND // - the tree is still balanced while (!(nodeStack.isEmpty() && node == null) && isBalanced) { // If the node is not null, we push it to the stack and continue // to the left if (node != null) { nodeStack.push(node); node = node.left; // Once we hit a node that is null, we are as deep as we can go // to the left } else { // Find the last node we put on the stack node = nodeStack.peek(); // If the right child of the node has either been visited or // is null, we visit this node if (node.right == null || node.right == lastVisited) { // We assume the left and right heights are 0 int leftHeight = 0; int rightHeight = 0; // If the right and left children are not null, we must // have already explored them and have a height // for them so let's get that if (node.left != null) { leftHeight = subtreeHeights.get(node.left); } if (node.right != null) { rightHeight = subtreeHeights.get(node.right); } // If the difference in the height of the right subtree // and left subtree differs by more than 1, we cannot be // balanced if (Math.abs(rightHeight - leftHeight) > 1) { isBalanced = false; } // The height of the subtree containing this node is the // max of the left and right subtree heights plus 1 subtreeHeights.put(node, Math.max(rightHeight, leftHeight) + 1); // We've now visited this node, so we pop it from the stack nodeStack.pop(); lastVisited = node; // Current visiting node is now null node = null; // If the right child node of this node has not been visited // and is not null, we need to get that child node on the stack } else { node = node.right; } } } // Return whether the tree is balanced return isBalanced; } }
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/trees/LazySegmentTree.java
src/main/java/com/thealgorithms/datastructures/trees/LazySegmentTree.java
package com.thealgorithms.datastructures.trees; public class LazySegmentTree { /** * Lazy Segment Tree * * @see * <a href="https://www.geeksforgeeks.org/lazy-propagation-in-segment-tree/"> */ static class Node { private final int start; private final int end; // start and end of the segment represented by this node private int value; // value is the sum of all elements in the range [start, end) private int lazy; // lazied value that should be added to children nodes Node left; Node right; // left and right children Node(int start, int end, int value) { this.start = start; this.end = end; this.value = value; this.lazy = 0; this.left = null; this.right = null; } /** * Update the value of this node with the given value diff. * * @param diff The value to add to every index of this node range. */ public void applyUpdate(int diff) { this.lazy += diff; this.value += (this.end - this.start) * diff; } /** * Shift the lazy value of this node to its children. */ public void shift() { if (lazy == 0) { return; } if (this.left == null && this.right == null) { return; } this.value += this.lazy; if (this.left != null) { this.left.applyUpdate(this.lazy); } if (this.right != null) { this.right.applyUpdate(this.lazy); } this.lazy = 0; } /** * Create a new node that is the sum of this node and the given node. * * @param left The left Node of merging * @param right The right Node of merging * @return The new Node. */ static Node merge(Node left, Node right) { if (left == null) { return right; } if (right == null) { return left; } Node result = new Node(left.start, right.end, left.value + right.value); result.left = left; result.right = right; return result; } public int getValue() { return value; } public Node getLeft() { return left; } public Node getRight() { return right; } } private final Node root; /** * Create a new LazySegmentTree with the given array. * * @param array The array to create the LazySegmentTree from. */ public LazySegmentTree(int[] array) { this.root = buildTree(array, 0, array.length); } /** * Build a new LazySegmentTree from the given array in O(n) time. * * @param array The array to build the LazySegmentTree from. * @param start The start index of the current node. * @param end The end index of the current node. * @return The root of the new LazySegmentTree. */ private Node buildTree(int[] array, int start, int end) { if (end - start < 2) { return new Node(start, end, array[start]); } int mid = (start + end) >> 1; Node left = buildTree(array, start, mid); Node right = buildTree(array, mid, end); return Node.merge(left, right); } /** * Update the value of given range with the given value diff in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. * @param diff The value to add to every index of the range. * @param curr The current node. */ private void updateRange(int left, int right, int diff, Node curr) { if (left <= curr.start && curr.end <= right) { curr.applyUpdate(diff); return; } if (left >= curr.end || right <= curr.start) { return; } curr.shift(); updateRange(left, right, diff, curr.left); updateRange(left, right, diff, curr.right); Node merge = Node.merge(curr.left, curr.right); curr.value = merge.value; } /** * Get Node of given range in O(log n) time. * * @param left The left index of the range to update. * @param right The right index of the range to update. * @return The Node representing the sum of the given range. */ private Node getRange(int left, int right, Node curr) { if (left <= curr.start && curr.end <= right) { return curr; } if (left >= curr.end || right <= curr.start) { return null; } curr.shift(); return Node.merge(getRange(left, right, curr.left), getRange(left, right, curr.right)); } public int getRange(int left, int right) { Node result = getRange(left, right, root); return result == null ? 0 : result.getValue(); } public void updateRange(int left, int right, int diff) { updateRange(left, right, diff, root); } public Node getRoot() { return root; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
src/main/java/com/thealgorithms/datastructures/trees/GenericTree.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.LinkedList; import java.util.Scanner; /** * A generic tree is a tree which can have as many children as it can be It * might be possible that every node present is directly connected to root node. * * <p> * In this code Every function has two copies: one function is helper function * which can be called from main and from that function a private function is * called which will do the actual work. I have done this, while calling from * main one have to give minimum parameters. */ public class GenericTree { private static final class Node { int data; ArrayList<Node> child = new ArrayList<>(); } private final Node root; public GenericTree() { // Constructor Scanner scn = new Scanner(System.in); root = createTreeG(null, 0, scn); } private Node createTreeG(Node node, int childIndex, Scanner scanner) { // display if (node == null) { System.out.println("Enter root's data"); } else { System.out.println("Enter data of parent of index " + node.data + " " + childIndex); } // input node = new Node(); node.data = scanner.nextInt(); System.out.println("number of children"); int number = scanner.nextInt(); for (int i = 0; i < number; i++) { Node child = createTreeG(node, i, scanner); node.child.add(child); } return node; } /** * Function to display the generic tree */ public void display() { // Helper function display1(root); } private void display1(Node parent) { System.out.print(parent.data + "=>"); for (int i = 0; i < parent.child.size(); i++) { System.out.print(parent.child.get(i).data + " "); } System.out.println("."); for (int i = 0; i < parent.child.size(); i++) { display1(parent.child.get(i)); } } /** * One call store the size directly but if you are asked compute size this * function to calculate size goes as follows * * @return size */ public int size2call() { return size2(root); } public int size2(Node roott) { int sz = 0; for (int i = 0; i < roott.child.size(); i++) { sz += size2(roott.child.get(i)); } return sz + 1; } /** * Function to compute maximum value in the generic tree * * @return maximum value */ public int maxcall() { int maxi = root.data; return max(root, maxi); } private int max(Node roott, int maxi) { if (maxi < roott.data) { maxi = roott.data; } for (int i = 0; i < roott.child.size(); i++) { maxi = max(roott.child.get(i), maxi); } return maxi; } /** * Function to compute HEIGHT of the generic tree * * @return height */ public int heightcall() { return height(root) - 1; } private int height(Node node) { int h = 0; for (int i = 0; i < node.child.size(); i++) { int k = height(node.child.get(i)); if (k > h) { h = k; } } return h + 1; } /** * Function to find whether a number is present in the generic tree or not * * @param info number * @return present or not */ public boolean findcall(int info) { return find(root, info); } private boolean find(Node node, int info) { if (node.data == info) { return true; } for (int i = 0; i < node.child.size(); i++) { if (find(node.child.get(i), info)) { return true; } } return false; } /** * Function to calculate depth of generic tree * * @param dep depth */ public void depthcaller(int dep) { depth(root, dep); } public void depth(Node node, int dep) { if (dep == 0) { System.out.println(node.data); return; } for (int i = 0; i < node.child.size(); i++) { depth(node.child.get(i), dep - 1); } } /** * Function to print generic tree in pre-order */ public void preordercall() { preorder(root); System.out.println("."); } private void preorder(Node node) { System.out.print(node.data + " "); for (int i = 0; i < node.child.size(); i++) { preorder(node.child.get(i)); } } /** * Function to print generic tree in post-order */ public void postordercall() { postorder(root); System.out.println("."); } private void postorder(Node node) { for (int i = 0; i < node.child.size(); i++) { postorder(node.child.get(i)); } System.out.print(node.data + " "); } /** * Function to print generic tree in level-order */ public void levelorder() { LinkedList<Node> q = new LinkedList<>(); q.addLast(root); while (!q.isEmpty()) { int k = q.getFirst().data; System.out.print(k + " "); for (int i = 0; i < q.getFirst().child.size(); i++) { q.addLast(q.getFirst().child.get(i)); } q.removeFirst(); } System.out.println("."); } /** * Function to remove all leaves of generic tree */ public void removeleavescall() { removeleaves(root); } private void removeleaves(Node node) { ArrayList<Integer> arr = new ArrayList<>(); for (int i = 0; i < node.child.size(); i++) { if (node.child.get(i).child.size() == 0) { arr.add(i); } else { removeleaves(node.child.get(i)); } } for (int i = arr.size() - 1; i >= 0; i--) { node.child.remove(arr.get(i) + 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/trees/BTree.java
src/main/java/com/thealgorithms/datastructures/trees/BTree.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; /** * Implementation of a B-Tree, a self-balancing tree data structure that maintains sorted data * and allows searches, sequential access, insertions, and deletions in logarithmic time. * * B-Trees are generalizations of binary search trees in that a node can have more than two children. * They're widely used in databases and file systems. * * For more information: https://en.wikipedia.org/wiki/B-tree */ public class BTree { static class BTreeNode { int[] keys; int t; // Minimum degree (defines range for number of keys) BTreeNode[] children; int n; // Current number of keys boolean leaf; BTreeNode(int t, boolean leaf) { this.t = t; this.leaf = leaf; this.keys = new int[2 * t - 1]; this.children = new BTreeNode[2 * t]; this.n = 0; } void traverse(ArrayList<Integer> result) { for (int i = 0; i < n; i++) { if (!leaf) { children[i].traverse(result); } result.add(keys[i]); } if (!leaf) { children[n].traverse(result); } } BTreeNode search(int key) { int i = 0; while (i < n && key > keys[i]) { i++; } if (i < n && keys[i] == key) { return this; } if (leaf) { return null; } return children[i].search(key); } void insertNonFull(int key) { int i = n - 1; if (leaf) { while (i >= 0 && keys[i] > key) { keys[i + 1] = keys[i]; i--; } keys[i + 1] = key; n++; } else { while (i >= 0 && keys[i] > key) { i--; } if (children[i + 1].n == 2 * t - 1) { splitChild(i + 1, children[i + 1]); if (keys[i + 1] < key) { i++; } } children[i + 1].insertNonFull(key); } } void splitChild(int i, BTreeNode y) { BTreeNode z = new BTreeNode(y.t, y.leaf); z.n = t - 1; System.arraycopy(y.keys, t, z.keys, 0, t - 1); if (!y.leaf) { System.arraycopy(y.children, t, z.children, 0, t); } y.n = t - 1; for (int j = n; j >= i + 1; j--) { children[j + 1] = children[j]; } children[i + 1] = z; for (int j = n - 1; j >= i; j--) { keys[j + 1] = keys[j]; } keys[i] = y.keys[t - 1]; n++; } void remove(int key) { int idx = findKey(key); if (idx < n && keys[idx] == key) { if (leaf) { removeFromLeaf(idx); } else { removeFromNonLeaf(idx); } } else { if (leaf) { return; // Key not found } boolean flag = idx == n; if (children[idx].n < t) { fill(idx); } if (flag && idx > n) { children[idx - 1].remove(key); } else { children[idx].remove(key); } } } private int findKey(int key) { int idx = 0; while (idx < n && keys[idx] < key) { ++idx; } return idx; } private void removeFromLeaf(int idx) { for (int i = idx + 1; i < n; ++i) { keys[i - 1] = keys[i]; } n--; } private void removeFromNonLeaf(int idx) { int key = keys[idx]; if (children[idx].n >= t) { int pred = getPredecessor(idx); keys[idx] = pred; children[idx].remove(pred); } else if (children[idx + 1].n >= t) { int succ = getSuccessor(idx); keys[idx] = succ; children[idx + 1].remove(succ); } else { merge(idx); children[idx].remove(key); } } private int getPredecessor(int idx) { BTreeNode cur = children[idx]; while (!cur.leaf) { cur = cur.children[cur.n]; } return cur.keys[cur.n - 1]; } private int getSuccessor(int idx) { BTreeNode cur = children[idx + 1]; while (!cur.leaf) { cur = cur.children[0]; } return cur.keys[0]; } private void fill(int idx) { if (idx != 0 && children[idx - 1].n >= t) { borrowFromPrev(idx); } else if (idx != n && children[idx + 1].n >= t) { borrowFromNext(idx); } else { if (idx != n) { merge(idx); } else { merge(idx - 1); } } } private void borrowFromPrev(int idx) { BTreeNode child = children[idx]; BTreeNode sibling = children[idx - 1]; for (int i = child.n - 1; i >= 0; --i) { child.keys[i + 1] = child.keys[i]; } if (!child.leaf) { for (int i = child.n; i >= 0; --i) { child.children[i + 1] = child.children[i]; } } child.keys[0] = keys[idx - 1]; if (!child.leaf) { child.children[0] = sibling.children[sibling.n]; } keys[idx - 1] = sibling.keys[sibling.n - 1]; child.n += 1; sibling.n -= 1; } private void borrowFromNext(int idx) { BTreeNode child = children[idx]; BTreeNode sibling = children[idx + 1]; child.keys[child.n] = keys[idx]; if (!child.leaf) { child.children[child.n + 1] = sibling.children[0]; } keys[idx] = sibling.keys[0]; for (int i = 1; i < sibling.n; ++i) { sibling.keys[i - 1] = sibling.keys[i]; } if (!sibling.leaf) { for (int i = 1; i <= sibling.n; ++i) { sibling.children[i - 1] = sibling.children[i]; } } child.n += 1; sibling.n -= 1; } private void merge(int idx) { BTreeNode child = children[idx]; BTreeNode sibling = children[idx + 1]; child.keys[t - 1] = keys[idx]; for (int i = 0; i < sibling.n; ++i) { child.keys[i + t] = sibling.keys[i]; } if (!child.leaf) { for (int i = 0; i <= sibling.n; ++i) { child.children[i + t] = sibling.children[i]; } } for (int i = idx + 1; i < n; ++i) { keys[i - 1] = keys[i]; } for (int i = idx + 2; i <= n; ++i) { children[i - 1] = children[i]; } child.n += sibling.n + 1; n--; } } private BTreeNode root; private final int t; public BTree(int t) { this.root = null; this.t = t; } public void traverse(ArrayList<Integer> result) { if (root != null) { root.traverse(result); } } public boolean search(int key) { return root != null && root.search(key) != null; } public void insert(int key) { if (search(key)) { return; } if (root == null) { root = new BTreeNode(t, true); root.keys[0] = key; root.n = 1; } else { if (root.n == 2 * t - 1) { BTreeNode s = new BTreeNode(t, false); s.children[0] = root; s.splitChild(0, root); int i = 0; if (s.keys[0] < key) { i++; } s.children[i].insertNonFull(key); root = s; } else { root.insertNonFull(key); } } } public void delete(int key) { if (root == null) { return; } root.remove(key); if (root.n == 0) { root = root.leaf ? null : root.children[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/trees/AVLSimple.java
src/main/java/com/thealgorithms/datastructures/trees/AVLSimple.java
package com.thealgorithms.datastructures.trees; /* * Avl is algo that balance itself while adding new values to tree * by rotating branches of binary tree and make itself Binary seaarch tree * there are four cases which has to tackle * rotating - left right ,left left,right right,right left Test Case: AVLTree tree=new AVLTree(); tree.insert(20); tree.insert(25); tree.insert(30); tree.insert(10); tree.insert(5); tree.insert(15); tree.insert(27); tree.insert(19); tree.insert(16); tree.display(); */ public class AVLSimple { private class Node { int data; int height; Node left; Node right; Node(int data) { this.data = data; this.height = 1; } } private Node root; public void insert(int data) { this.root = insert(this.root, data); } private Node insert(Node node, int item) { if (node == null) { return new Node(item); } if (node.data > item) { node.left = insert(node.left, item); } if (node.data < item) { node.right = insert(node.right, item); } node.height = Math.max(height(node.left), height(node.right)) + 1; int bf = bf(node); // LL case if (bf > 1 && item < node.left.data) { return rightRotate(node); } // RR case if (bf < -1 && item > node.right.data) { return leftRotate(node); } // RL case if (bf < -1 && item < node.right.data) { node.right = rightRotate(node.right); return leftRotate(node); } // LR case if (bf > 1 && item > node.left.data) { node.left = leftRotate(node.left); return rightRotate(node); } return node; } public void display() { this.display(this.root); System.out.println(this.root.height); } private void display(Node node) { String str = ""; if (node.left != null) { str += node.left.data + "=>"; } else { str += "END=>"; } str += node.data + ""; if (node.right != null) { str += "<=" + node.right.data; } else { str += "<=END"; } System.out.println(str); if (node.left != null) { display(node.left); } if (node.right != null) { display(node.right); } } private int height(Node node) { if (node == null) { return 0; } return node.height; } private int bf(Node node) { if (node == null) { return 0; } return height(node.left) - height(node.right); } private Node rightRotate(Node c) { Node b = c.left; Node t3 = b.right; b.right = c; c.left = t3; c.height = Math.max(height(c.left), height(c.right)) + 1; b.height = Math.max(height(b.left), height(b.right)) + 1; return b; } private Node leftRotate(Node c) { Node b = c.right; Node t3 = b.left; b.left = c; c.right = t3; c.height = Math.max(height(c.left), height(c.right)) + 1; b.height = Math.max(height(b.left), height(b.right)) + 1; return 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/datastructures/trees/SameTreesCheck.java
src/main/java/com/thealgorithms/datastructures/trees/SameTreesCheck.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayDeque; import java.util.Deque; /** * Given 2 binary trees. * This code checks whether they are the same (structurally identical and have the same values) or * not. <p> Example: * 1. Binary trees: * 1 1 * / \ / \ * 2 3 2 3 * /\ /\ /\ /\ * 4 5 6 7 4 5 6 7 * These trees are the same, so the code returns 'true'. * <p> * 2. Binary trees: * 1 1 * / \ * 2 2 * These trees are NOT the same (the structure differs), so the code returns 'false'. * <p> * This solution implements the breadth-first search (BFS) algorithm. * For each tree we create a queue and iterate the trees using these queues. * On each step we check the nodes for equality, and if the nodes are not the same, return false. * Otherwise, add children nodes to the queues and continue traversing the trees. * <p> * Complexities: * O(N) - time, where N is the number of nodes in a binary tree, * O(N) - space, where N is the number of nodes in a binary tree. * * @author Albina Gimaletdinova on 13/01/2023 */ public final class SameTreesCheck { private SameTreesCheck() { } public static boolean check(BinaryTree.Node p, BinaryTree.Node q) { if (p == null && q == null) { return true; } if (p == null || q == null) { return false; } Deque<BinaryTree.Node> q1 = new ArrayDeque<>(); Deque<BinaryTree.Node> q2 = new ArrayDeque<>(); q1.add(p); q2.add(q); while (!q1.isEmpty() && !q2.isEmpty()) { BinaryTree.Node first = q1.poll(); BinaryTree.Node second = q2.poll(); // check that some node can be null // if the check is true: both nodes are null or both nodes are not null if (!equalNodes(first, second)) { return false; } if (first != null) { if (!equalNodes(first.left, second.left)) { return false; } if (first.left != null) { q1.add(first.left); q2.add(second.left); } if (!equalNodes(first.right, second.right)) { return false; } if (first.right != null) { q1.add(first.right); q2.add(second.right); } } } return true; } private static boolean equalNodes(BinaryTree.Node p, BinaryTree.Node q) { if (p == null && q == null) { return true; } if (p == null || q == null) { return false; } return p.data == q.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/datastructures/trees/BSTRecursiveGeneric.java
src/main/java/com/thealgorithms/datastructures/trees/BSTRecursiveGeneric.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.List; /** * <h1>Binary Search Tree (Recursive) Generic Type Implementation</h1> * * <p> * A recursive implementation of generic type BST. * * Reference: <a href="https://en.wikipedia.org/wiki/Binary_search_tree">Wiki links for BST</a> * </p> * * @author [Madhur Panwar](<a href="https://github.com/mdrpanwar">git-Madhur Panwar</a>) * @author [Udaya Krishnan M](<a href="https://github.com/UdayaKrishnanM/">git-Udaya Krishnan M</a>) {added prettyDisplay() method} */ public class BSTRecursiveGeneric<T extends Comparable<T>> { /** * only data member is root of BST */ private Node<T> root; /** * Constructor use to initialize node as null */ public BSTRecursiveGeneric() { root = null; } /** * Displays the tree is a structured format */ public void prettyDisplay() { prettyDisplay(root, 0); } private void prettyDisplay(Node<T> node, int level) { if (node == null) { return; } prettyDisplay(node.right, level + 1); if (level != 0) { for (int i = 0; i < level - 1; i++) { System.out.print("|\t"); } System.out.println("|---->" + node.data); } else { System.out.println(node.data); } prettyDisplay(node.left, level + 1); } /** * main function for testing */ public static void main(String[] args) { System.out.println("Testing for integer data..."); // Integer BSTRecursiveGeneric<Integer> integerTree = new BSTRecursiveGeneric<Integer>(); integerTree.add(5); integerTree.add(10); integerTree.add(-9); integerTree.add(4); integerTree.add(3); integerTree.add(1); System.out.println("Pretty Display of current tree is:"); integerTree.prettyDisplay(); assert !integerTree.find(4) : "4 is not yet present in BST"; assert integerTree.find(10) : "10 should be present in BST"; integerTree.remove(9); assert !integerTree.find(9) : "9 was just deleted from BST"; integerTree.remove(1); assert !integerTree.find(1) : "Since 1 was not present so find deleting would do no change"; integerTree.add(20); integerTree.add(70); assert integerTree.find(70) : "70 was inserted but not found"; /* Will print in following order 5 10 20 70 */ System.out.println("Pretty Display of current tree is:"); integerTree.prettyDisplay(); integerTree.inorder(); System.out.println("Pretty Display of current tree is:"); integerTree.prettyDisplay(); System.out.println(); System.out.println("Testing for string data..."); // String BSTRecursiveGeneric<String> stringTree = new BSTRecursiveGeneric<String>(); stringTree.add("banana"); stringTree.add("apple"); stringTree.add("pineapple"); stringTree.add("date"); assert !stringTree.find("girl") : "girl is not yet present in BST"; assert stringTree.find("pineapple") : "10 should be present in BST"; stringTree.remove("date"); assert !stringTree.find("date") : "date was just deleted from BST"; stringTree.remove("boy"); assert !stringTree.find("boy") : "Since boy was not present so deleting would do no change"; stringTree.add("india"); stringTree.add("hills"); assert stringTree.find("hills") : "hills was inserted but not found"; System.out.println("Pretty Display of current tree is:"); stringTree.prettyDisplay(); /* Will print in following order banana hills india pineapple */ stringTree.inorder(); System.out.println("Pretty Display of current tree is:"); stringTree.prettyDisplay(); } /** * Recursive method to delete a data if present in BST. * * @param node the node under which to (recursively) search for data * @param data the value to be deleted * @return Node the updated value of root parameter after delete operation */ private Node<T> delete(Node<T> node, T data) { if (node == null) { System.out.println("No such data present in BST."); } else if (node.data.compareTo(data) > 0) { node.left = delete(node.left, data); } else if (node.data.compareTo(data) < 0) { node.right = delete(node.right, data); } else { if (node.right == null && node.left == null) { // If it is leaf node node = null; } else if (node.left == null) { // If only right node is present Node<T> temp = node.right; node.right = null; node = temp; } else if (node.right == null) { // Only left node is present Node<T> temp = node.left; node.left = null; node = temp; } else { // both child are present Node<T> temp = node.right; // Find leftmost child of right subtree while (temp.left != null) { temp = temp.left; } node.data = temp.data; node.right = delete(node.right, temp.data); } } return node; } /** * Recursive insertion of value in BST. * * @param node to check if the data can be inserted in current node or its * subtree * @param data the value to be inserted * @return the modified value of the root parameter after insertion */ private Node<T> insert(Node<T> node, T data) { if (node == null) { node = new Node<>(data); } else if (node.data.compareTo(data) > 0) { node.left = insert(node.left, data); } else if (node.data.compareTo(data) < 0) { node.right = insert(node.right, data); } return node; } /** * Recursively print Preorder traversal of the BST * * @param node the root node */ private void preOrder(Node<T> node) { if (node == null) { return; } System.out.print(node.data + " "); if (node.left != null) { preOrder(node.left); } if (node.right != null) { preOrder(node.right); } } /** * Recursively print Postorder traversal of BST. * * @param node the root node */ private void postOrder(Node<T> node) { if (node == null) { return; } if (node.left != null) { postOrder(node.left); } if (node.right != null) { postOrder(node.right); } System.out.print(node.data + " "); } /** * Recursively print Inorder traversal of BST. * * @param node the root node */ private void inOrder(Node<T> node) { if (node == null) { return; } if (node.left != null) { inOrder(node.left); } System.out.print(node.data + " "); if (node.right != null) { inOrder(node.right); } } /** * Recursively traverse the tree using inorder traversal and keep adding * elements to argument list. * * @param node the root node * @param sortedList the list to add the srted elements into */ private void inOrderSort(Node<T> node, List<T> sortedList) { if (node == null) { return; } if (node.left != null) { inOrderSort(node.left, sortedList); } sortedList.add(node.data); if (node.right != null) { inOrderSort(node.right, sortedList); } } /** * Search recursively if the given value is present in BST or not. * * @param node the node under which to check * @param data the value to be checked * @return boolean if data is present or not */ private boolean search(Node<T> node, T data) { if (node == null) { return false; } else if (node.data.compareTo(data) == 0) { return true; } else if (node.data.compareTo(data) > 0) { return search(node.left, data); } else { return search(node.right, data); } } /** * add in BST. if the value is not already present it is inserted or else no * change takes place. * * @param data the value to be inserted */ public void add(T data) { this.root = insert(this.root, data); } /** * If data is present in BST delete it else do nothing. * * @param data the value to be removed */ public void remove(T data) { this.root = delete(this.root, data); } /** * To call inorder traversal on tree */ public void inorder() { System.out.println("Inorder traversal of this tree is:"); inOrder(this.root); System.out.println(); // for next line } /** * return a sorted list by traversing the tree elements using inorder * traversal */ public List<T> inorderSort() { List<T> sortedList = new ArrayList<>(); inOrderSort(this.root, sortedList); return sortedList; } /** * To call postorder traversal on tree */ public void postorder() { System.out.println("Postorder traversal of this tree is:"); postOrder(this.root); System.out.println(); // for next line } /** * To call preorder traversal on tree. */ public void preorder() { System.out.println("Preorder traversal of this tree is:"); preOrder(this.root); System.out.println(); // for next line } /** * To check if given value is present in tree or not. * * @param data the data to be found for */ public boolean find(T data) { if (search(this.root, data)) { System.out.println(data + " is present in given BST."); return true; } System.out.println(data + " not found."); return false; } /** * The generic Node class used for building binary search tree */ private static class Node<T> { T data; Node<T> left; Node<T> right; /** * Constructor with data as parameter */ Node(T d) { data = d; left = null; right = 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/trees/CheckTreeIsSymmetric.java
src/main/java/com/thealgorithms/datastructures/trees/CheckTreeIsSymmetric.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * Check if a binary tree is symmetric or not. * A binary tree is a symmetric tree if the left and right subtree of root are mirror image. * Below is a symmetric tree * 1 * / \ * 2 2 * / \ / \ * 3 4 4 3 * * Below is not symmetric because values is different in last level * 1 * / \ * 2 2 * / \ / \ * 3 5 4 3 * <p> * Approach: * Recursively check for left and right subtree of root * 1. left subtrees root's values should be equal right subtree's root value * 2. recursively check with left subtrees' left child VS right subtree's right child AND * left subtree's right child VS right subtree left child * Complexity * 1. Time: O(n) * 2. Space: O(lg(n)) for height of tree * * @author kumanoit on 10/10/22 IST 12:52 AM */ public final class CheckTreeIsSymmetric { private CheckTreeIsSymmetric() { } public static boolean isSymmetric(Node root) { if (root == null) { return true; } return isSymmetric(root.left, root.right); } private static boolean isSymmetric(Node leftSubtreeRoot, Node rightSubtreeRoot) { if (leftSubtreeRoot == null && rightSubtreeRoot == null) { return true; } if (isInvalidSubtree(leftSubtreeRoot, rightSubtreeRoot)) { return false; } return isSymmetric(leftSubtreeRoot.right, rightSubtreeRoot.left) && isSymmetric(leftSubtreeRoot.left, rightSubtreeRoot.right); } private static boolean isInvalidSubtree(Node leftSubtreeRoot, Node rightSubtreeRoot) { return leftSubtreeRoot == null || rightSubtreeRoot == null || leftSubtreeRoot.data != rightSubtreeRoot.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/datastructures/trees/SplayTree.java
src/main/java/com/thealgorithms/datastructures/trees/SplayTree.java
package com.thealgorithms.datastructures.trees; import java.util.LinkedList; import java.util.List; /** * Implementation of a Splay Tree data structure. * * A splay tree is a self-adjusting binary search tree with the additional * property * that recently accessed elements are quick to access again. It performs basic * operations such as insertion, deletion, and searching in O(log n) amortized * time, * where n is the number of elements in the tree. * * The key feature of splay trees is the splay operation, which moves a node * closer * to the root of the tree when it is accessed. This operation helps to maintain * good balance and improves the overall performance of the tree. After * performing * a splay operation, the accessed node becomes the new root of the tree. * * Splay trees have applications in various areas, including caching, network * routing, * and dynamic optimality analysis. */ public class SplayTree { public static final TreeTraversal PRE_ORDER = new PreOrderTraversal(); public static final TreeTraversal IN_ORDER = new InOrderTraversal(); public static final TreeTraversal POST_ORDER = new PostOrderTraversal(); private Node root; /** * Checks if the tree is empty. * * @return True if the tree is empty, otherwise false. */ public boolean isEmpty() { return root == null; } /** * Insert a key into the SplayTree. * * @param key The key to insert. */ public void insert(final int key) { root = insertRec(root, key); root = splay(root, key); } /** * Search for a key in the SplayTree. * * @param key The key to search for. * @return True if the key is found, otherwise false. */ public boolean search(int key) { root = splay(root, key); return root != null && root.key == key; } /** * Deletes a key from the SplayTree. * * @param key The key to delete. * @throws IllegalArgumentException If the tree is empty. */ public void delete(final int key) { if (isEmpty()) { throw new EmptyTreeException("Cannot delete from an empty tree"); } root = splay(root, key); if (root.key != key) { return; } if (root.left == null) { root = root.right; } else { Node temp = root; root = splay(root.left, findMax(root.left).key); root.right = temp.right; } } /** * Perform a traversal of the SplayTree. * * @param traversal The type of traversal method. * @return A list containing the keys in the specified traversal order. */ public List<Integer> traverse(TreeTraversal traversal) { List<Integer> result = new LinkedList<>(); traversal.traverse(root, result); return result; } /** * Finds the node with the maximum key in a given subtree. * * <p> * This method traverses the right children of the subtree until it finds the * rightmost node, which contains the maximum key. * </p> * * @param root The root node of the subtree. * @return The node with the maximum key in the subtree. */ private Node findMax(Node root) { while (root.right != null) { root = root.right; } return root; } /** * Zig operation. * * <p> * The zig operation is used to perform a single rotation on a node to move it * closer to * the root of the tree. It is typically applied when the node is a left child * of its parent * and needs to be rotated to the right. * </p> * * @param x The node to perform the zig operation on. * @return The new root node after the operation. */ private Node rotateRight(Node x) { Node y = x.left; x.left = y.right; y.right = x; return y; } /** * Zag operation. * * <p> * The zag operation is used to perform a single rotation on a node to move it * closer to * the root of the tree. It is typically applied when the node is a right child * of its parent * and needs to be rotated to the left. * </p> * * @param x The node to perform the zag operation on. * @return The new root node after the operation. */ private Node rotateLeft(Node x) { Node y = x.right; x.right = y.left; y.left = x; return y; } /** * Splay operation. * * <p> * The splay operation is the core operation of a splay tree. It moves a * specified node * closer to the root of the tree by performing a series of rotations. The goal * of the splay * operation is to improve the access time for frequently accessed nodes by * bringing them * closer to the root. * </p> * * <p> * The splay operation consists of three main cases: * <ul> * <li>Zig-Zig case: Perform two consecutive rotations.</li> * <li>Zig-Zag case: Perform two consecutive rotations in opposite * directions.</li> * <li>Zag-Zag case: Perform two consecutive rotations.</li> * </ul> * </p> * * <p> * After performing the splay operation, the accessed node becomes the new root * of the tree. * </p> * * @param root The root of the subtree to splay. * @param key The key to splay around. * @return The new root of the splayed subtree. */ private Node splay(Node root, final int key) { if (root == null || root.key == key) { return root; } if (root.key > key) { if (root.left == null) { return root; } // Zig-Zig case if (root.left.key > key) { root.left.left = splay(root.left.left, key); root = rotateRight(root); } else if (root.left.key < key) { root.left.right = splay(root.left.right, key); if (root.left.right != null) { root.left = rotateLeft(root.left); } } return (root.left == null) ? root : rotateRight(root); } else { if (root.right == null) { return root; } // Zag-Zag case if (root.right.key > key) { root.right.left = splay(root.right.left, key); if (root.right.left != null) { root.right = rotateRight(root.right); } } else if (root.right.key < key) { root.right.right = splay(root.right.right, key); root = rotateLeft(root); } return (root.right == null) ? root : rotateLeft(root); } } private Node insertRec(Node root, final int key) { if (root == null) { return new Node(key); } if (key < root.key) { root.left = insertRec(root.left, key); } else if (key > root.key) { root.right = insertRec(root.right, key); } else { throw new DuplicateKeyException("Duplicate key: " + key); } return root; } public static class EmptyTreeException extends RuntimeException { private static final long serialVersionUID = 1L; public EmptyTreeException(String message) { super(message); } } public static class DuplicateKeyException extends RuntimeException { private static final long serialVersionUID = 1L; public DuplicateKeyException(String message) { super(message); } } private static class Node { final int key; Node left; Node right; Node(int key) { this.key = key; left = null; right = null; } } public interface TreeTraversal { /** * Recursive function for a specific order traversal. * * @param root The root of the subtree to traverse. * @param result The list to store the traversal result. */ void traverse(Node root, List<Integer> result); } private static final class InOrderTraversal implements TreeTraversal { private InOrderTraversal() { } public void traverse(Node root, List<Integer> result) { if (root != null) { traverse(root.left, result); result.add(root.key); traverse(root.right, result); } } } private static final class PreOrderTraversal implements TreeTraversal { private PreOrderTraversal() { } public void traverse(Node root, List<Integer> result) { if (root != null) { result.add(root.key); traverse(root.left, result); traverse(root.right, result); } } } private static final class PostOrderTraversal implements TreeTraversal { private PostOrderTraversal() { } public void traverse(Node root, List<Integer> result) { if (root != null) { traverse(root.left, result); traverse(root.right, result); result.add(root.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/trees/BSTRecursive.java
src/main/java/com/thealgorithms/datastructures/trees/BSTRecursive.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * * * <h1>Binary Search Tree (Recursive)</h1> * * An implementation of BST recursively. In recursive implementation the checks * are down the tree First root is checked if not found then its children are * checked Binary Search Tree is a binary tree which satisfies three properties: * left child is less than root node, right child is grater than root node, both * left and right children must themselves be a BST. * * <p> * I have made public functions as methods and to actually implement recursive * approach I have used private methods * * @author [Lakhan Nad](<a href="https://github.com/Lakhan-Nad">git-Lakhan Nad</a>) */ public class BSTRecursive { /** * only data member is root of BST */ private Node root; /** * Constructor use to initialize node as null */ BSTRecursive() { root = null; } public Node getRoot() { return root; } /** * Recursive method to delete a data if present in BST. * * @param node the current node to search for data * @param data the value to be deleted * @return Node the updated value of root parameter after delete operation */ private Node delete(Node node, int data) { if (node == null) { System.out.println("No such data present in BST."); } else if (node.data > data) { node.left = delete(node.left, data); } else if (node.data < data) { node.right = delete(node.right, data); } else { if (node.right == null && node.left == null) { // If it is leaf node node = null; } else if (node.left == null) { // If only right node is present Node temp = node.right; node.right = null; node = temp; } else if (node.right == null) { // Only left node is present Node temp = node.left; node.left = null; node = temp; } else { // both children are present Node temp = node.right; // Find leftmost child of right subtree while (temp.left != null) { temp = temp.left; } node.data = temp.data; node.right = delete(node.right, temp.data); } } return node; } /** * Recursive insertion of value in BST. * * @param node to check if the data can be inserted in current node or its * subtree * @param data the value to be inserted * @return the modified value of the root parameter after insertion */ private Node insert(Node node, int data) { if (node == null) { node = new Node(data); } else if (node.data > data) { node.left = insert(node.left, data); } else if (node.data < data) { node.right = insert(node.right, data); } return node; } /** * Search recursively if the given value is present in BST or not. * * @param node the current node to check * @param data the value to be checked * @return boolean if data is present or not */ private boolean search(Node node, int data) { if (node == null) { return false; } else if (node.data == data) { return true; } else if (node.data > data) { return search(node.left, data); } else { return search(node.right, data); } } /** * add in BST. if the value is not already present it is inserted or else no * change takes place. * * @param data the value to be inserted */ public void add(int data) { this.root = insert(this.root, data); } /** * If data is present in BST delete it else do nothing. * * @param data the value to be removed */ public void remove(int data) { this.root = delete(this.root, data); } /** * To check if given value is present in tree or not. * * @param data the data to be found for */ public boolean find(int data) { if (search(this.root, data)) { System.out.println(data + " is present in given BST."); return true; } System.out.println(data + " not found."); 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/trees/CentroidDecomposition.java
src/main/java/com/thealgorithms/datastructures/trees/CentroidDecomposition.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Centroid Decomposition is a divide-and-conquer technique for trees. * It recursively partitions a tree by finding centroids - nodes whose removal * creates balanced subtrees (each with at most N/2 nodes). * * <p> * Time Complexity: O(N log N) for construction * Space Complexity: O(N) * * <p> * Applications: * - Distance queries on trees * - Path counting problems * - Nearest neighbor searches * * @see <a href="https://en.wikipedia.org/wiki/Centroid_decomposition">Centroid Decomposition</a> * @see <a href="https://codeforces.com/blog/entry/81661">Centroid Decomposition Tutorial</a> * @author lens161 */ public final class CentroidDecomposition { private CentroidDecomposition() { } /** * Represents the centroid tree structure. */ public static final class CentroidTree { private final int n; private final List<List<Integer>> adj; private final int[] parent; private final int[] subtreeSize; private final boolean[] removed; private int root; /** * Constructs a centroid tree from an adjacency list. * * @param adj adjacency list representation of the tree (0-indexed) * @throws IllegalArgumentException if tree is empty or null */ public CentroidTree(List<List<Integer>> adj) { if (adj == null || adj.isEmpty()) { throw new IllegalArgumentException("Tree cannot be empty or null"); } this.n = adj.size(); this.adj = adj; this.parent = new int[n]; this.subtreeSize = new int[n]; this.removed = new boolean[n]; Arrays.fill(parent, -1); // Build centroid tree starting from node 0 this.root = decompose(0, -1); } /** * Recursively builds the centroid tree. * * @param u current node * @param p parent in centroid tree * @return centroid of current component */ private int decompose(int u, int p) { int size = getSubtreeSize(u, -1); int centroid = findCentroid(u, -1, size); removed[centroid] = true; parent[centroid] = p; // Recursively decompose each subtree for (int v : adj.get(centroid)) { if (!removed[v]) { decompose(v, centroid); } } return centroid; } /** * Calculates subtree size from node u. * * @param u current node * @param p parent node (-1 for root) * @return size of subtree rooted at u */ private int getSubtreeSize(int u, int p) { subtreeSize[u] = 1; for (int v : adj.get(u)) { if (v != p && !removed[v]) { subtreeSize[u] += getSubtreeSize(v, u); } } return subtreeSize[u]; } /** * Finds the centroid of a subtree. * A centroid is a node whose removal creates components with size &lt;= totalSize/2. * * @param u current node * @param p parent node * @param totalSize total size of current component * @return centroid node */ private int findCentroid(int u, int p, int totalSize) { for (int v : adj.get(u)) { if (v != p && !removed[v] && subtreeSize[v] > totalSize / 2) { return findCentroid(v, u, totalSize); } } return u; } /** * Gets the parent of a node in the centroid tree. * * @param node the node * @return parent node in centroid tree, or -1 if root */ public int getParent(int node) { if (node < 0 || node >= n) { throw new IllegalArgumentException("Invalid node: " + node); } return parent[node]; } /** * Gets the root of the centroid tree. * * @return root node */ public int getRoot() { return root; } /** * Gets the number of nodes in the tree. * * @return number of nodes */ public int size() { return n; } /** * Returns the centroid tree structure as a string. * Format: node -&gt; parent (or ROOT for root node) * * @return string representation */ @Override public String toString() { StringBuilder sb = new StringBuilder("Centroid Tree:\n"); for (int i = 0; i < n; i++) { sb.append("Node ").append(i).append(" -> "); if (parent[i] == -1) { sb.append("ROOT"); } else { sb.append("Parent ").append(parent[i]); } sb.append("\n"); } return sb.toString(); } } /** * Creates a centroid tree from an edge list. * * @param n number of nodes (0-indexed: 0 to n-1) * @param edges list of edges where each edge is [u, v] * @return CentroidTree object * @throws IllegalArgumentException if n &lt;= 0 or edges is invalid */ public static CentroidTree buildFromEdges(int n, int[][] edges) { if (n <= 0) { throw new IllegalArgumentException("Number of nodes must be positive"); } if (edges == null) { throw new IllegalArgumentException("Edges cannot be null"); } if (edges.length != n - 1) { throw new IllegalArgumentException("Tree must have exactly n-1 edges"); } List<List<Integer>> adj = new ArrayList<>(); for (int i = 0; i < n; i++) { adj.add(new ArrayList<>()); } for (int[] edge : edges) { if (edge.length != 2) { throw new IllegalArgumentException("Each edge must have exactly 2 nodes"); } int u = edge[0]; int v = edge[1]; if (u < 0 || u >= n || v < 0 || v >= n) { throw new IllegalArgumentException("Invalid node in edge: [" + u + ", " + v + "]"); } adj.get(u).add(v); adj.get(v).add(u); } return new CentroidTree(adj); } }
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/trees/RedBlackBST.java
src/main/java/com/thealgorithms/datastructures/trees/RedBlackBST.java
package com.thealgorithms.datastructures.trees; import java.util.Scanner; /** * @author jack870131 */ public class RedBlackBST { private static final int RED = 0; private static final int BLACK = 1; private class Node { int key = -1; int color = BLACK; Node left = nil; Node right = nil; Node p = nil; Node(int key) { this.key = key; } } private final Node nil = new Node(-1); private Node root = nil; public void printTree(Node node) { if (node == nil) { return; } printTree(node.left); System.out.print(((node.color == RED) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); printTree(node.right); } public void printTreepre(Node node) { if (node == nil) { return; } System.out.print(((node.color == RED) ? " R " : " B ") + "Key: " + node.key + " Parent: " + node.p.key + "\n"); printTreepre(node.left); printTreepre(node.right); } private Node findNode(Node findNode, Node node) { if (root == nil) { return null; } if (findNode.key < node.key) { if (node.left != nil) { return findNode(findNode, node.left); } } else if (findNode.key > node.key) { if (node.right != nil) { return findNode(findNode, node.right); } } else if (findNode.key == node.key) { return node; } return null; } private void insert(Node node) { Node temp = root; if (root == nil) { root = node; node.color = BLACK; node.p = nil; } else { node.color = RED; while (true) { if (node.key < temp.key) { if (temp.left == nil) { temp.left = node; node.p = temp; break; } else { temp = temp.left; } } else if (node.key >= temp.key) { if (temp.right == nil) { temp.right = node; node.p = temp; break; } else { temp = temp.right; } } } fixTree(node); } } private void fixTree(Node node) { while (node.p.color == RED) { Node y = nil; if (node.p == node.p.p.left) { y = node.p.p.right; if (y != nil && y.color == RED) { node.p.color = BLACK; y.color = BLACK; node.p.p.color = RED; node = node.p.p; continue; } if (node == node.p.right) { node = node.p; rotateLeft(node); } node.p.color = BLACK; node.p.p.color = RED; rotateRight(node.p.p); } else { y = node.p.p.left; if (y != nil && y.color == RED) { node.p.color = BLACK; y.color = BLACK; node.p.p.color = RED; node = node.p.p; continue; } if (node == node.p.left) { node = node.p; rotateRight(node); } node.p.color = BLACK; node.p.p.color = RED; rotateLeft(node.p.p); } } root.color = BLACK; } void rotateLeft(Node node) { if (node.p != nil) { if (node == node.p.left) { node.p.left = node.right; } else { node.p.right = node.right; } node.right.p = node.p; node.p = node.right; if (node.right.left != nil) { node.right.left.p = node; } node.right = node.right.left; node.p.left = node; } else { Node right = root.right; root.right = right.left; right.left.p = root; root.p = right; right.left = root; right.p = nil; root = right; } } void rotateRight(Node node) { if (node.p != nil) { if (node == node.p.left) { node.p.left = node.left; } else { node.p.right = node.left; } node.left.p = node.p; node.p = node.left; if (node.left.right != nil) { node.left.right.p = node; } node.left = node.left.right; node.p.right = node; } else { Node left = root.left; root.left = root.left.right; left.right.p = root; root.p = left; left.right = root; left.p = nil; root = left; } } void transplant(Node target, Node with) { if (target.p == nil) { root = with; } else if (target == target.p.left) { target.p.left = with; } else { target.p.right = with; } with.p = target.p; } Node treeMinimum(Node subTreeRoot) { while (subTreeRoot.left != nil) { subTreeRoot = subTreeRoot.left; } return subTreeRoot; } boolean delete(Node z) { Node result = findNode(z, root); if (result == null) { return false; } Node x; Node y = z; int yorigcolor = y.color; if (z.left == nil) { x = z.right; transplant(z, z.right); } else if (z.right == nil) { x = z.left; transplant(z, z.left); } else { y = treeMinimum(z.right); yorigcolor = y.color; x = y.right; if (y.p == z) { x.p = y; } else { transplant(y, y.right); y.right = z.right; y.right.p = y; } transplant(z, y); y.left = z.left; y.left.p = y; y.color = z.color; } if (yorigcolor == BLACK) { deleteFixup(x); } return true; } void deleteFixup(Node x) { while (x != root && x.color == BLACK) { if (x == x.p.left) { Node w = x.p.right; if (w.color == RED) { w.color = BLACK; x.p.color = RED; rotateLeft(x.p); w = x.p.right; } if (w.left.color == BLACK && w.right.color == BLACK) { w.color = RED; x = x.p; continue; } else if (w.right.color == BLACK) { w.left.color = BLACK; w.color = RED; rotateRight(w); w = x.p.right; } if (w.right.color == RED) { w.color = x.p.color; x.p.color = BLACK; w.right.color = BLACK; rotateLeft(x.p); x = root; } } else { Node w = x.p.left; if (w.color == RED) { w.color = BLACK; x.p.color = RED; rotateRight(x.p); w = x.p.left; } if (w.right.color == BLACK && w.left.color == BLACK) { w.color = RED; x = x.p; continue; } else if (w.left.color == BLACK) { w.right.color = BLACK; w.color = RED; rotateLeft(w); w = x.p.left; } if (w.left.color == RED) { w.color = x.p.color; x.p.color = BLACK; w.left.color = BLACK; rotateRight(x.p); x = root; } } } x.color = BLACK; } public void insertDemo() { Scanner scan = new Scanner(System.in); System.out.println("Add items"); int item; Node node; item = scan.nextInt(); while (item != -999) { node = new Node(item); insert(node); item = scan.nextInt(); } printTree(root); System.out.println("Pre order"); printTreepre(root); scan.close(); } public void deleteDemo() { Scanner scan = new Scanner(System.in); System.out.println("Delete items"); int item; Node node; item = scan.nextInt(); node = new Node(item); System.out.print("Deleting item " + item); if (delete(node)) { System.out.print(": deleted!"); } else { System.out.print(": does not exist!"); } System.out.println(); printTree(root); System.out.println("Pre order"); printTreepre(root); scan.close(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
src/main/java/com/thealgorithms/datastructures/trees/CheckBinaryTreeIsValidBST.java
package com.thealgorithms.datastructures.trees; /** * This code recursively validates whether given Binary Search Tree (BST) is balanced or not. * Trees with only distinct values are supported. * Key points: * 1. According to the definition of a BST, each node in a tree must be in range [min, max], * where 'min' and 'max' values represent the child nodes (left, right). * 2. The smallest possible node value is Integer.MIN_VALUE, the biggest - Integer.MAX_VALUE. */ public final class CheckBinaryTreeIsValidBST { private CheckBinaryTreeIsValidBST() { } public static boolean isBST(BinaryTree.Node root) { return isBSTUtil(root, Integer.MIN_VALUE, Integer.MAX_VALUE); } private static boolean isBSTUtil(BinaryTree.Node node, int min, int max) { // empty tree is a BST if (node == null) { return true; } if (node.data < min || node.data > max) { return false; } return (isBSTUtil(node.left, min, node.data - 1) && isBSTUtil(node.right, node.data + 1, max)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
src/main/java/com/thealgorithms/datastructures/trees/AVLTree.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.List; /** * Represents an AVL Tree, a self-balancing binary search tree. * In an AVL tree, the heights of the two child subtrees of any node * differ by at most one. If they differ by more than one at any time, * rebalancing is performed to restore this property. */ public class AVLTree { private Node root; private static class Node { private int key; private int balance; private int height; private Node left; private Node right; private Node parent; Node(int k, Node p) { key = k; parent = p; } public Integer getBalance() { return balance; } } /** * Inserts a new key into the AVL tree. * * @param key the key to be inserted * @return {@code true} if the key was inserted, {@code false} if the key already exists */ public boolean insert(int key) { if (root == null) { root = new Node(key, null); } else { Node n = root; Node parent; while (true) { if (n.key == key) { return false; } parent = n; boolean goLeft = n.key > key; n = goLeft ? n.left : n.right; if (n == null) { if (goLeft) { parent.left = new Node(key, parent); } else { parent.right = new Node(key, parent); } rebalance(parent); break; } } } return true; } /** * Deletes a key from the AVL tree. * * @param delKey the key to be deleted */ public void delete(int delKey) { if (root == null) { return; } // Find the node to be deleted Node node = root; Node child = root; while (child != null) { node = child; child = delKey >= node.key ? node.right : node.left; if (delKey == node.key) { delete(node); return; } } } private void delete(Node node) { if (node.left == null && node.right == null) { // Leaf node if (node.parent == null) { root = null; } else { Node parent = node.parent; if (parent.left == node) { parent.left = null; } else { parent.right = null; } rebalance(parent); } return; } // Node has one or two children Node child; if (node.left != null) { child = node.left; while (child.right != null) { child = child.right; } } else { child = node.right; while (child.left != null) { child = child.left; } } node.key = child.key; delete(child); } /** * Returns a list of balance factors for each node in the tree. * * @return a list of integers representing the balance factors of the nodes */ public List<Integer> returnBalance() { List<Integer> balances = new ArrayList<>(); returnBalance(root, balances); return balances; } private void returnBalance(Node n, List<Integer> balances) { if (n != null) { returnBalance(n.left, balances); balances.add(n.getBalance()); returnBalance(n.right, balances); } } /** * Searches for a key in the AVL tree. * * @param key the key to be searched * @return true if the key is found, false otherwise */ public boolean search(int key) { Node result = searchHelper(this.root, key); return result != null; } private Node searchHelper(Node root, int key) { if (root == null || root.key == key) { return root; } if (root.key > key) { return searchHelper(root.left, key); } return searchHelper(root.right, key); } private void rebalance(Node n) { setBalance(n); if (n.balance == -2) { if (height(n.left.left) >= height(n.left.right)) { n = rotateRight(n); } else { n = rotateLeftThenRight(n); } } else if (n.balance == 2) { if (height(n.right.right) >= height(n.right.left)) { n = rotateLeft(n); } else { n = rotateRightThenLeft(n); } } if (n.parent != null) { rebalance(n.parent); } else { root = n; } } private Node rotateLeft(Node a) { Node b = a.right; b.parent = a.parent; a.right = b.left; if (a.right != null) { a.right.parent = a; } b.left = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateRight(Node a) { Node b = a.left; b.parent = a.parent; a.left = b.right; if (a.left != null) { a.left.parent = a; } b.right = a; a.parent = b; if (b.parent != null) { if (b.parent.right == a) { b.parent.right = b; } else { b.parent.left = b; } } setBalance(a, b); return b; } private Node rotateLeftThenRight(Node n) { n.left = rotateLeft(n.left); return rotateRight(n); } private Node rotateRightThenLeft(Node n) { n.right = rotateRight(n.right); return rotateLeft(n); } private int height(Node n) { if (n == null) { return -1; } return n.height; } private void setBalance(Node... nodes) { for (Node n : nodes) { reheight(n); n.balance = height(n.right) - height(n.left); } } private void reheight(Node node) { if (node != null) { node.height = 1 + Math.max(height(node.left), height(node.right)); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java
src/main/java/com/thealgorithms/datastructures/trees/ThreadedBinaryTree.java
/* * TheAlgorithms (https://github.com/TheAlgorithms/Java) * Author: Shewale41 * This file is licensed under the MIT License. */ package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.List; /** * Threaded binary tree implementation that supports insertion and * in-order traversal without recursion or stack by using threads. * * <p>In this implementation, a node's null left/right pointers are used * to point to the in-order predecessor/successor respectively. Two flags * indicate whether left/right pointers are real children or threads. * * @see <a href="https://en.wikipedia.org/wiki/Threaded_binary_tree">Wikipedia: * Threaded binary tree</a> */ public final class ThreadedBinaryTree { private Node root; private static final class Node { int value; Node left; Node right; boolean leftIsThread; boolean rightIsThread; Node(int value) { this.value = value; this.left = null; this.right = null; this.leftIsThread = false; this.rightIsThread = false; } } public ThreadedBinaryTree() { this.root = null; } /** * Inserts a value into the threaded binary tree. Duplicate values are inserted * to the right subtree (consistent deterministic rule). * * @param value the integer value to insert */ public void insert(int value) { Node newNode = new Node(value); if (root == null) { root = newNode; return; } Node current = root; Node parent = null; while (true) { parent = current; if (value < current.value) { if (!current.leftIsThread && current.left != null) { current = current.left; } else { break; } } else { // value >= current.value if (!current.rightIsThread && current.right != null) { current = current.right; } else { break; } } } if (value < parent.value) { // attach newNode as left child newNode.left = parent.left; newNode.leftIsThread = parent.leftIsThread; newNode.right = parent; newNode.rightIsThread = true; parent.left = newNode; parent.leftIsThread = false; } else { // attach newNode as right child newNode.right = parent.right; newNode.rightIsThread = parent.rightIsThread; newNode.left = parent; newNode.leftIsThread = true; parent.right = newNode; parent.rightIsThread = false; } } /** * Returns the in-order traversal of the tree as a list of integers. * Traversal is done without recursion or an explicit stack by following threads. * * @return list containing the in-order sequence of node values */ public List<Integer> inorderTraversal() { List<Integer> result = new ArrayList<>(); Node current = root; if (current == null) { return result; } // Move to the leftmost node while (current.left != null && !current.leftIsThread) { current = current.left; } while (current != null) { result.add(current.value); // If right pointer is a thread, follow it if (current.rightIsThread) { current = current.right; } else { // Move to leftmost node in right subtree current = current.right; while (current != null && !current.leftIsThread && current.left != null) { current = current.left; } } } return result; } /** * Helper: checks whether the tree is empty. * * @return true if tree has no nodes */ public boolean isEmpty() { return root == 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/trees/KDTree.java
src/main/java/com/thealgorithms/datastructures/trees/KDTree.java
package com.thealgorithms.datastructures.trees; import java.util.Arrays; import java.util.Comparator; import java.util.Objects; import java.util.Optional; /* * K-D Tree Implementation * Wikipedia: https://en.wikipedia.org/wiki/K-d_tree * * Author: Amir Hosseini (https://github.com/itsamirhn) * * */ public class KDTree { private Node root; private final int k; // Dimensions of the points /** * Constructor for empty KDTree * * @param k Number of dimensions */ KDTree(int k) { this.k = k; } /** * Builds the KDTree from the specified points * * @param points Array of initial points */ KDTree(Point[] points) { if (points.length == 0) { throw new IllegalArgumentException("Points array cannot be empty"); } this.k = points[0].getDimension(); for (Point point : points) { if (point.getDimension() != k) { throw new IllegalArgumentException("Points must have the same dimension"); } } this.root = build(points, 0); } /** * Builds the KDTree from the specified coordinates of the points * * @param pointsCoordinates Array of initial points coordinates * */ KDTree(int[][] pointsCoordinates) { if (pointsCoordinates.length == 0) { throw new IllegalArgumentException("Points array cannot be empty"); } this.k = pointsCoordinates[0].length; Point[] points = Arrays.stream(pointsCoordinates).map(Point::new).toArray(Point[] ::new); for (Point point : points) { if (point.getDimension() != k) { throw new IllegalArgumentException("Points must have the same dimension"); } } this.root = build(points, 0); } static class Point { int[] coordinates; public int getCoordinate(int i) { return coordinates[i]; } public int getDimension() { return coordinates.length; } Point(int[] coordinates) { this.coordinates = coordinates; } @Override public boolean equals(Object obj) { if (obj instanceof Point other) { return Arrays.equals(other.coordinates, this.coordinates); } return false; } @Override public int hashCode() { return Arrays.hashCode(coordinates); } @Override public String toString() { return Arrays.toString(coordinates); } /** * Find the comparable distance between two points (without SQRT) * * @param p1 First point * @param p2 Second point * * @return The comparable distance between the two points */ public static int comparableDistance(Point p1, Point p2) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { int t = p1.getCoordinate(i) - p2.getCoordinate(i); distance += t * t; } return distance; } /** * Find the comparable distance between two points with ignoring specified axis * * @param p1 First point * @param p2 Second point * @param axis The axis to ignore * * @return The distance between the two points */ public static int comparableDistanceExceptAxis(Point p1, Point p2, int axis) { int distance = 0; for (int i = 0; i < p1.getDimension(); i++) { if (i == axis) { continue; } int t = p1.getCoordinate(i) - p2.getCoordinate(i); distance += t * t; } return distance; } } static class Node { private Point point; private int axis; // 0 for x, 1 for y, 2 for z, etc. private Node left = null; // Left child private Node right = null; // Right child Node(Point point, int axis) { this.point = point; this.axis = axis; } public Point getPoint() { return point; } public Node getLeft() { return left; } public Node getRight() { return right; } public int getAxis() { return axis; } /** * Get the nearest child according to the specified point * * @param point The point to find the nearest child to * * @return The nearest child Node */ public Node getNearChild(Point point) { if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) { return left; } else { return right; } } /** * Get the farthest child according to the specified point * * @param point The point to find the farthest child to * * @return The farthest child Node */ public Node getFarChild(Point point) { if (point.getCoordinate(axis) < this.point.getCoordinate(axis)) { return right; } else { return left; } } /** * Get the node axis coordinate of point * * @return The axis coordinate of the point */ public int getAxisCoordinate() { return point.getCoordinate(axis); } } public Node getRoot() { return root; } /** * Builds the KDTree from the specified points * * @param points Array of initial points * @param depth The current depth of the tree * * @return The root of the KDTree */ private Node build(Point[] points, int depth) { if (points.length == 0) { return null; } int axis = depth % k; if (points.length == 1) { return new Node(points[0], axis); } Arrays.sort(points, Comparator.comparingInt(o -> o.getCoordinate(axis))); int median = points.length >> 1; Node node = new Node(points[median], axis); node.left = build(Arrays.copyOfRange(points, 0, median), depth + 1); node.right = build(Arrays.copyOfRange(points, median + 1, points.length), depth + 1); return node; } /** * Insert a point into the KDTree * * @param point The point to insert * */ public void insert(Point point) { if (point.getDimension() != k) { throw new IllegalArgumentException("Point has wrong dimension"); } root = insert(root, point, 0); } /** * Insert a point into a subtree * * @param root The root of the subtree * @param point The point to insert * @param depth The current depth of the tree * * @return The root of the KDTree */ private Node insert(Node root, Point point, int depth) { int axis = depth % k; if (root == null) { return new Node(point, axis); } if (point.getCoordinate(axis) < root.getAxisCoordinate()) { root.left = insert(root.left, point, depth + 1); } else { root.right = insert(root.right, point, depth + 1); } return root; } /** * Search for Node corresponding to the specified point in the KDTree * * @param point The point to search for * * @return The Node corresponding to the specified point */ public Optional<Node> search(Point point) { if (point.getDimension() != k) { throw new IllegalArgumentException("Point has wrong dimension"); } return search(root, point); } /** * Search for Node corresponding to the specified point in a subtree * * @param root The root of the subtree to search in * @param point The point to search for * * @return The Node corresponding to the specified point */ public Optional<Node> search(Node root, Point point) { if (root == null) { return Optional.empty(); } if (root.point.equals(point)) { return Optional.of(root); } return search(root.getNearChild(point), point); } /** * Find a point with minimum value in specified axis in the KDTree * * @param axis The axis to find the minimum value in * * @return The point with minimum value in the specified axis */ public Point findMin(int axis) { return findMin(root, axis).point; } /** * Find a point with minimum value in specified axis in a subtree * * @param root The root of the subtree to search in * @param axis The axis to find the minimum value in * * @return The Node with minimum value in the specified axis of the point */ public Node findMin(Node root, int axis) { if (root == null) { return null; } if (root.getAxis() == axis) { if (root.left == null) { return root; } return findMin(root.left, axis); } else { Node left = findMin(root.left, axis); Node right = findMin(root.right, axis); Node[] candidates = {left, root, right}; return Arrays.stream(candidates).filter(Objects::nonNull).min(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null); } } /** * Find a point with maximum value in specified axis in the KDTree * * @param axis The axis to find the maximum value in * * @return The point with maximum value in the specified axis */ public Point findMax(int axis) { return findMax(root, axis).point; } /** * Find a point with maximum value in specified axis in a subtree * * @param root The root of the subtree to search in * @param axis The axis to find the maximum value in * * @return The Node with maximum value in the specified axis of the point */ public Node findMax(Node root, int axis) { if (root == null) { return null; } if (root.getAxis() == axis) { if (root.right == null) { return root; } return findMax(root.right, axis); } else { Node left = findMax(root.left, axis); Node right = findMax(root.right, axis); Node[] candidates = {left, root, right}; return Arrays.stream(candidates).filter(Objects::nonNull).max(Comparator.comparingInt(a -> a.point.getCoordinate(axis))).orElse(null); } } /** * Delete the node with the given point. * * @param point the point to delete * */ public void delete(Point point) { Node node = search(point).orElseThrow(() -> new IllegalArgumentException("Point not found")); root = delete(root, node); } /** * Delete the specified node from a subtree. * * @param root The root of the subtree to delete from * @param node The node to delete * * @return The new root of the subtree */ private Node delete(Node root, Node node) { if (root == null) { return null; } if (root.equals(node)) { if (root.right != null) { Node min = findMin(root.right, root.getAxis()); root.point = min.point; root.right = delete(root.right, min); } else if (root.left != null) { Node min = findMin(root.left, root.getAxis()); root.point = min.point; root.left = delete(root.left, min); } else { return null; } } if (root.getAxisCoordinate() < node.point.getCoordinate(root.getAxis())) { root.left = delete(root.left, node); } else { root.right = delete(root.right, node); } return root; } /** * Finds the nearest point in the tree to the given point. * * @param point The point to find the nearest neighbor to. * */ public Point findNearest(Point point) { return findNearest(root, point, root).point; } /** * Finds the nearest point in a subtree to the given point. * * @param root The root of the subtree to search in. * @param point The point to find the nearest neighbor to. * @param nearest The nearest neighbor found so far. * */ private Node findNearest(Node root, Point point, Node nearest) { if (root == null) { return nearest; } if (root.point.equals(point)) { return root; } int distance = Point.comparableDistance(root.point, point); int distanceExceptAxis = Point.comparableDistanceExceptAxis(root.point, point, root.getAxis()); if (distance < Point.comparableDistance(nearest.point, point)) { nearest = root; } nearest = findNearest(root.getNearChild(point), point, nearest); if (distanceExceptAxis < Point.comparableDistance(nearest.point, point)) { nearest = findNearest(root.getFarChild(point), point, nearest); } return nearest; } }
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/trees/CeilInBinarySearchTree.java
src/main/java/com/thealgorithms/datastructures/trees/CeilInBinarySearchTree.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * Problem Statement Ceil value for any number x in a collection is a number y * which is either equal to x or the least greater number than x. * * Problem: Given a binary search tree containing positive integer values. Find * ceil value for a given key in O(lg(n)) time. In case if it is not present * return -1. * * Ex.1. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 10. Answer: 20 * * Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 22 Answer: 25 * * Ex.2. [30,20,40,10,25,35,50] represents level order traversal of a binary * search tree. Find ceil for 52 Answer: -1 * * Solution 1: Brute Force Solution: Do an inorder traversal and save result * into an array. Iterate over the array to get an element equal to or greater * than current key. Time Complexity: O(n) Space Complexity: O(n) for auxiliary * array to save inorder representation of tree. * <p> * <p> * Solution 2: Brute Force Solution: Do an inorder traversal and save result * into an array.Since array is sorted do a binary search over the array to get * an element equal to or greater than current key. Time Complexity: O(n) for * traversal of tree and O(lg(n)) for binary search in array. Total = O(n) Space * Complexity: O(n) for auxiliary array to save inorder representation of tree. * <p> * <p> * Solution 3: Optimal We can do a DFS search on given tree in following * fashion. i) if root is null then return null because then ceil doesn't exist * ii) If key is lesser than root value than ceil will be in right subtree so * call recursively on right subtree iii) if key is greater than current root, * then either a) the root is ceil b) ceil is in left subtree: call for left * subtree. If left subtree returns a non-null value then that will be ceil * otherwise the root is ceil */ public final class CeilInBinarySearchTree { private CeilInBinarySearchTree() { } public static Node getCeil(Node root, int key) { if (root == null) { return null; } // if root value is same as key than root is the ceiling if (root.data == key) { return root; } // if root value is lesser than key then ceil must be in right subtree if (root.data < key) { return getCeil(root.right, key); } // if root value is greater than key then ceil can be in left subtree or if // it is not in left subtree then current node will be ceil Node result = getCeil(root.left, key); // if result is null it means that there is no ceil in children subtrees // and the root is the ceil otherwise the returned node is the ceil. return result == null ? root : 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/trees/VerticalOrderTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/VerticalOrderTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; /* The following class implements a vertical order traversal in a tree from top to bottom and left to right, so for a tree : 1 / \ 2 3 / \ \ 4 5 6 \ / \ 7 8 10 \ 9 the sequence will be : 4 2 7 1 5 9 3 8 6 10 */ public final class VerticalOrderTraversal { private VerticalOrderTraversal() { } /*Function that receives a root Node and prints the tree in Vertical Order.*/ public static ArrayList<Integer> verticalTraversal(BinaryTree.Node root) { if (root == null) { return new ArrayList<>(); } /*Queue to store the Nodes.*/ Queue<BinaryTree.Node> queue = new LinkedList<>(); /*Queue to store the index of particular vertical column of a tree , with root at 0, Nodes on left with negative index and Nodes on right with positive index. */ Queue<Integer> index = new LinkedList<>(); /*Map of Integer and ArrayList to store all the elements in a particular index in a single arrayList that will have a key equal to the index itself. */ Map<Integer, ArrayList<Integer>> map = new HashMap<>(); /* min and max stores leftmost and right most index to later print the tree in vertical fashion.*/ int max = 0; int min = 0; queue.offer(root); index.offer(0); while (!queue.isEmpty()) { if (queue.peek().left != null) { /*Adding the left Node if it is not null and its index by subtracting 1 from it's parent's index*/ queue.offer(queue.peek().left); index.offer(index.peek() - 1); } if (queue.peek().right != null) { /*Adding the right Node if it is not null and its index by adding 1 from it's parent's index*/ queue.offer(queue.peek().right); index.offer(index.peek() + 1); } /*If the map does not contains the index a new ArrayList is created with the index as key.*/ if (!map.containsKey(index.peek())) { ArrayList<Integer> a = new ArrayList<>(); map.put(index.peek(), a); } /*For a index, corresponding Node data is added to the respective ArrayList present at that index. */ map.get(index.peek()).add(queue.peek().data); max = Math.max(max, index.peek()); min = Math.min(min, index.peek()); /*The Node and its index are removed from their respective queues.*/ index.poll(); queue.poll(); } /*Finally map data is printed here which has keys from min to max. Each ArrayList represents a vertical column that is added in ans ArrayList.*/ ArrayList<Integer> ans = new ArrayList<>(); for (int i = min; i <= max; i++) { ans.addAll(map.get(i)); } return ans; } }
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/trees/BinaryTreeToString.java
src/main/java/com/thealgorithms/datastructures/trees/BinaryTreeToString.java
package com.thealgorithms.datastructures.trees; /** * Leetcode 606: Construct String from Binary Tree: * https://leetcode.com/problems/construct-string-from-binary-tree/ * * Utility class to convert a {@link BinaryTree} into its string representation. * <p> * The conversion follows a preorder traversal pattern (root → left → right) * and uses parentheses to denote the tree structure. * Empty parentheses "()" are used to explicitly represent missing left children * when a right child exists, ensuring the structure is unambiguous. * </p> * * <h2>Rules:</h2> * <ul> * <li>Each node is represented as {@code (value)}.</li> * <li>If a node has only a right child, include {@code ()} before the right * child * to indicate the missing left child.</li> * <li>If a node has no children, it appears as just {@code (value)}.</li> * <li>The outermost parentheses are removed from the final string.</li> * </ul> * * <h3>Example:</h3> * * <pre> * Input tree: * 1 * / \ * 2 3 * \ * 4 * * Output string: * "1(2()(4))(3)" * </pre> * * <p> * This implementation matches the logic from LeetCode problem 606: * <i>Construct String from Binary Tree</i>. * </p> * * @author Muhammad Junaid * @see BinaryTree */ public class BinaryTreeToString { /** String builder used to accumulate the string representation. */ private StringBuilder sb; /** * Converts a binary tree (given its root node) to its string representation. * * @param root the root node of the binary tree * @return the string representation of the binary tree, or an empty string if * the tree is null */ public String tree2str(BinaryTree.Node root) { if (root == null) { return ""; } sb = new StringBuilder(); dfs(root); // Remove the leading and trailing parentheses added by the root call return sb.substring(1, sb.length() - 1); } /** * Performs a recursive depth-first traversal to build the string. * Each recursive call appends the node value and its children (if any) * enclosed in parentheses. * * @param node the current node being processed */ private void dfs(BinaryTree.Node node) { if (node == null) { return; } sb.append("(").append(node.data); // Recursively build left and right subtrees if (node.left != null) { dfs(node.left); } // Handle the special case: right child exists but left child is null if (node.right != null && node.left == null) { sb.append("()"); dfs(node.right); } else if (node.right != null) { dfs(node.right); } sb.append(")"); } }
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/trees/LCA.java
src/main/java/com/thealgorithms/datastructures/trees/LCA.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.Scanner; public final class LCA { private LCA() { } private static final Scanner SCANNER = new Scanner(System.in); public static void main(String[] args) { // The adjacency list representation of a tree: ArrayList<ArrayList<Integer>> adj = new ArrayList<>(); // v is the number of vertices and e is the number of edges int v = SCANNER.nextInt(); int e = v - 1; for (int i = 0; i < v; i++) { adj.add(new ArrayList<Integer>()); } // Storing the given tree as an adjacency list int to; int from; for (int i = 0; i < e; i++) { to = SCANNER.nextInt(); from = SCANNER.nextInt(); adj.get(to).add(from); adj.get(from).add(to); } // parent[v1] gives parent of a vertex v1 int[] parent = new int[v]; // depth[v1] gives depth of vertex v1 with respect to the root int[] depth = new int[v]; // Assuming the tree to be rooted at 0, hence calculating parent and depth of every vertex dfs(adj, 0, -1, parent, depth); // Inputting the two vertices whose LCA is to be calculated int v1 = SCANNER.nextInt(); int v2 = SCANNER.nextInt(); // Outputting the LCA System.out.println(getLCA(v1, v2, depth, parent)); } /** * Depth first search to calculate parent and depth of every vertex * * @param adj The adjacency list representation of the tree * @param s The source vertex * @param p Parent of source * @param parent An array to store parents of all vertices * @param depth An array to store depth of all vertices */ private static void dfs(ArrayList<ArrayList<Integer>> adj, int s, int p, int[] parent, int[] depth) { for (int adjacent : adj.get(s)) { if (adjacent != p) { parent[adjacent] = s; depth[adjacent] = 1 + depth[s]; dfs(adj, adjacent, s, parent, depth); } } } /** * Method to calculate Lowest Common Ancestor * * @param v1 The first vertex * @param v2 The second vertex * @param depth An array with depths of all vertices * @param parent An array with parents of all vertices * @return Returns a vertex that is LCA of v1 and v2 */ private static int getLCA(int v1, int v2, int[] depth, int[] parent) { if (depth[v1] < depth[v2]) { int temp = v1; v1 = v2; v2 = temp; } while (depth[v1] != depth[v2]) { v1 = parent[v1]; } if (v1 == v2) { return v1; } while (v1 != v2) { v1 = parent[v1]; v2 = parent[v2]; } return v1; } } /* * Input: * 10 * 0 1 * 0 2 * 1 5 * 5 6 * 2 4 * 2 3 * 3 7 * 7 9 * 7 8 * 9 4 * Output: * 2 */
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/LevelOrderTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; public final class LevelOrderTraversal { private LevelOrderTraversal() { } public static List<List<Integer>> traverse(BinaryTree.Node root) { if (root == null) { return List.of(); } List<List<Integer>> result = new ArrayList<>(); Queue<BinaryTree.Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { int nodesOnLevel = q.size(); List<Integer> level = new LinkedList<>(); for (int i = 0; i < nodesOnLevel; i++) { BinaryTree.Node tempNode = q.poll(); level.add(tempNode.data); if (tempNode.left != null) { q.add(tempNode.left); } if (tempNode.right != null) { q.add(tempNode.right); } } result.add(level); } return result; } /* Print nodes at the given level */ public static void printGivenLevel(BinaryTree.Node root, int level) { if (root == null) { System.out.println("Root node must not be null! Exiting."); return; } if (level == 1) { System.out.print(root.data + " "); } else if (level > 1) { printGivenLevel(root.left, level - 1); printGivenLevel(root.right, level - 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/datastructures/trees/SegmentTree.java
src/main/java/com/thealgorithms/datastructures/trees/SegmentTree.java
package com.thealgorithms.datastructures.trees; public class SegmentTree { private int[] segTree; private int n; private int[] arr; /* Constructor which takes the size of the array and the array as a parameter*/ public SegmentTree(int n, int[] arr) { this.n = n; int x = (int) (Math.ceil(Math.log(n) / Math.log(2))); int segSize = 2 * (int) Math.pow(2, x) - 1; this.segTree = new int[segSize]; this.arr = arr; this.n = n; constructTree(arr, 0, n - 1, 0); } /* A function which will create the segment tree*/ public final int constructTree(int[] arr, int start, int end, int index) { if (start == end) { this.segTree[index] = arr[start]; return arr[start]; } int mid = start + (end - start) / 2; this.segTree[index] = constructTree(arr, start, mid, index * 2 + 1) + constructTree(arr, mid + 1, end, index * 2 + 2); return this.segTree[index]; } /* A function which will update the value at a index i. This will be called by the update function internally*/ private void updateTree(int start, int end, int index, int diff, int segIndex) { if (index < start || index > end) { return; } this.segTree[segIndex] += diff; if (start != end) { int mid = start + (end - start) / 2; updateTree(start, mid, index, diff, segIndex * 2 + 1); updateTree(mid + 1, end, index, diff, segIndex * 2 + 2); } } /* A function to update the value at a particular index*/ public void update(int index, int value) { if (index < 0 || index > n) { return; } int diff = value - arr[index]; arr[index] = value; updateTree(0, n - 1, index, diff, 0); } /* A function to get the sum of the elements from index l to index r. This will be called * internally*/ private int getSumTree(int start, int end, int qStart, int qEnd, int segIndex) { if (qStart <= start && qEnd >= end) { return this.segTree[segIndex]; } if (qStart > end || qEnd < start) { return 0; } int mid = start + (end - start) / 2; return (getSumTree(start, mid, qStart, qEnd, segIndex * 2 + 1) + getSumTree(mid + 1, end, qStart, qEnd, segIndex * 2 + 2)); } /* A function to query the sum of the subarray [start...end]*/ public int getSum(int start, int end) { if (start < 0 || end > n || start > end) { return 0; } return getSumTree(0, n - 1, start, end, 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/trees/BinaryTree.java
src/main/java/com/thealgorithms/datastructures/trees/BinaryTree.java
package com.thealgorithms.datastructures.trees; import java.util.LinkedList; import java.util.Queue; /* * This entire class is used to build a Binary Tree data structure. There is the * Node Class and the Tree Class, both explained below. */ /** * A binary tree is a data structure in which an element has two * successors(children). The left child is usually smaller than the parent, and * the right child is usually bigger. * * @author Unknown */ public class BinaryTree { /** * This class implements the nodes that will go on the Binary Tree. They * consist of the data in them, the node to the left, the node to the right, * and the parent from which they came from. * * @author Unknown */ static class Node { /** * Data for the node */ public int data; /** * The Node to the left of this one */ public Node left; /** * The Node to the right of this one */ public Node right; /** * The parent of this node */ public Node parent; /** * Constructor of Node * * @param value Value to put in the node */ Node(int value) { data = value; left = null; right = null; parent = null; } } /** * The root of the Binary Tree */ private Node root; /** * Constructor */ public BinaryTree() { root = null; } /** * Parameterized Constructor */ public BinaryTree(Node root) { this.root = root; } /** * Method to find a Node with a certain value * * @param key Value being looked for * @return The node if it finds it, otherwise returns the parent */ public Node find(int key) { Node current = root; while (current != null) { if (key < current.data) { if (current.left == null) { return current; // The key isn't exist, returns the parent } current = current.left; } else if (key > current.data) { if (current.right == null) { return current; } current = current.right; } else { // If you find the value return it return current; } } return null; } /** * Inserts certain value into the Binary Tree * * @param value Value to be inserted */ public void put(int value) { Node newNode = new Node(value); if (root == null) { root = newNode; } else { // This will return the soon to be parent of the value you're inserting Node parent = find(value); // This if/else assigns the new node to be either the left or right child of the parent if (value < parent.data) { parent.left = newNode; parent.left.parent = parent; } else { parent.right = newNode; parent.right.parent = parent; } } } /** * Deletes a given value from the Binary Tree * * @param value Value to be deleted * @return If the value was deleted */ public boolean remove(int value) { // temp is the node to be deleted Node temp = find(value); // If the value doesn't exist if (temp.data != value) { return false; } // No children if (temp.right == null && temp.left == null) { if (temp == root) { root = null; } // This if/else assigns the new node to be either the left or right child of the // parent else if (temp.parent.data < temp.data) { temp.parent.right = null; } else { temp.parent.left = null; } return true; } // Two children else if (temp.left != null && temp.right != null) { Node successor = findSuccessor(temp); // The left tree of temp is made the left tree of the successor successor.left = temp.left; successor.left.parent = successor; // If the successor has a right child, the child's grandparent is it's new parent if (successor.parent != temp) { if (successor.right != null) { successor.right.parent = successor.parent; successor.parent.left = successor.right; } else { successor.parent.left = null; } successor.right = temp.right; successor.right.parent = successor; } if (temp == root) { successor.parent = null; root = successor; } // If you're not deleting the root else { successor.parent = temp.parent; // This if/else assigns the new node to be either the left or right child of the // parent if (temp.parent.data < temp.data) { temp.parent.right = successor; } else { temp.parent.left = successor; } } return true; } // One child else { // If it has a right child if (temp.right != null) { if (temp == root) { root = temp.right; return true; } temp.right.parent = temp.parent; // Assigns temp to left or right child if (temp.data < temp.parent.data) { temp.parent.left = temp.right; } else { temp.parent.right = temp.right; } } // If it has a left child else { if (temp == root) { root = temp.left; return true; } temp.left.parent = temp.parent; // Assigns temp to left or right side if (temp.data < temp.parent.data) { temp.parent.left = temp.left; } else { temp.parent.right = temp.left; } } return true; } } /** * This method finds the Successor to the Node given. Move right once and go * left down the tree as far as you can * * @param n Node that you want to find the Successor of * @return The Successor of the node */ public Node findSuccessor(Node n) { if (n.right == null) { return n; } Node current = n.right; Node parent = n.right; while (current != null) { parent = current; current = current.left; } return parent; } /** * Returns the root of the Binary Tree * * @return the root of the Binary Tree */ public Node getRoot() { return root; } /** * Prints leftChild - root - rightChild This is the equivalent of a depth * first search * * @param localRoot The local root of the binary tree */ public void inOrder(Node localRoot) { if (localRoot != null) { inOrder(localRoot.left); System.out.print(localRoot.data + " "); inOrder(localRoot.right); } } /** * Prints root - leftChild - rightChild * * @param localRoot The local root of the binary tree */ public void preOrder(Node localRoot) { if (localRoot != null) { System.out.print(localRoot.data + " "); preOrder(localRoot.left); preOrder(localRoot.right); } } /** * Prints leftChild - rightChild - root * * @param localRoot The local root of the binary tree */ public void postOrder(Node localRoot) { if (localRoot != null) { postOrder(localRoot.left); postOrder(localRoot.right); System.out.print(localRoot.data + " "); } } /** * Prints the tree in a breadth first search order This is similar to * pre-order traversal, but instead of being implemented with a stack (or * recursion), it is implemented with a queue * * @param localRoot The local root of the binary tree */ public void bfs(Node localRoot) { // Create a queue for the order of the nodes Queue<Node> queue = new LinkedList<>(); // If the give root is null, then we don't add to the queue // and won't do anything if (localRoot != null) { queue.add(localRoot); } // Continue until the queue is empty while (!queue.isEmpty()) { // Get the next node on the queue to visit localRoot = queue.remove(); // Print the data from the node we are visiting System.out.print(localRoot.data + " "); // Add the children to the queue if not null if (localRoot.right != null) { queue.add(localRoot.right); } if (localRoot.left != null) { queue.add(localRoot.left); } } } }
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/trees/PostOrderTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/PostOrderTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * Given tree is traversed in a 'post-order' way: LEFT -> RIGHT -> ROOT. * Below are given the recursive and iterative implementations. * <p> * Complexities: * Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree. * <p> * Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 * \ * 6 * \ * 7 * \ * 8 * * @author Albina Gimaletdinova on 21/02/2023 */ public final class PostOrderTraversal { private PostOrderTraversal() { } public static List<Integer> recursivePostOrder(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); recursivePostOrder(root, result); return result; } public static List<Integer> iterativePostOrder(BinaryTree.Node root) { LinkedList<Integer> result = new LinkedList<>(); if (root == null) { return result; } Deque<BinaryTree.Node> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { BinaryTree.Node node = stack.pop(); result.addFirst(node.data); if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return result; } private static void recursivePostOrder(BinaryTree.Node root, List<Integer> result) { if (root == null) { return; } recursivePostOrder(root.left, result); recursivePostOrder(root.right, result); result.add(root.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/datastructures/trees/BSTFromSortedArray.java
src/main/java/com/thealgorithms/datastructures/trees/BSTFromSortedArray.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * Given a sorted array. Create a balanced binary search tree from it. * * Steps: 1. Find the middle element of array. This will act as root 2. Use the * left half recursively to create left subtree 3. Use the right half * recursively to create right subtree */ public final class BSTFromSortedArray { private BSTFromSortedArray() { } public static Node createBST(int[] array) { if (array == null || array.length == 0) { return null; } return createBST(array, 0, array.length - 1); } private static Node createBST(int[] array, int startIdx, int endIdx) { // No element left. if (startIdx > endIdx) { return null; } int mid = startIdx + (endIdx - startIdx) / 2; // middle element will be the root Node root = new Node(array[mid]); root.left = createBST(array, startIdx, mid - 1); root.right = createBST(array, mid + 1, endIdx); return root; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/BoundaryTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/BoundaryTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * BoundaryTraversal * <p> * Start with the Root: * Add the root node to the boundary list. * Traverse the Left Boundary (Excluding Leaf Nodes): * Move down the left side of the tree, adding each non-leaf node to the boundary list. * If a node has a left child, go left; otherwise, go right. * Visit All Leaf Nodes: * Traverse the tree and add all leaf nodes to the boundary list, from left to right. * Traverse the Right Boundary (Excluding Leaf Nodes) in Reverse Order: * Move up the right side of the tree, adding each non-leaf node to a temporary list. * If a node has a right child, go right; otherwise, go left. * Reverse the temporary list and add it to the boundary list. * Combine and Output: * The final boundary list contains the root, left boundary, leaf nodes, and reversed right boundary in that order. */ public final class BoundaryTraversal { private BoundaryTraversal() { } // Main function for boundary traversal, returns a list of boundary nodes in order public static List<Integer> boundaryTraversal(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } // Add root node if it's not a leaf node if (!isLeaf(root)) { result.add(root.data); } // Add left boundary addLeftBoundary(root, result); // Add leaf nodes addLeaves(root, result); // Add right boundary addRightBoundary(root, result); return result; } // Adds the left boundary, including nodes that have no left child but have a right child private static void addLeftBoundary(BinaryTree.Node node, List<Integer> result) { BinaryTree.Node cur = node.left; // If there is no left child but there is a right child, treat the right child as part of the left boundary if (cur == null && node.right != null) { cur = node.right; } while (cur != null) { if (!isLeaf(cur)) { result.add(cur.data); // Add non-leaf nodes to result } if (cur.left != null) { cur = cur.left; // Move to the left child } else if (cur.right != null) { cur = cur.right; // If left child is null, move to the right child } else { break; // Stop if there are no children } } } // Adds leaf nodes (nodes without children) private static void addLeaves(BinaryTree.Node node, List<Integer> result) { if (node == null) { return; } if (isLeaf(node)) { result.add(node.data); // Add leaf node } else { addLeaves(node.left, result); // Recur for left subtree addLeaves(node.right, result); // Recur for right subtree } } // Adds the right boundary, excluding leaf nodes private static void addRightBoundary(BinaryTree.Node node, List<Integer> result) { BinaryTree.Node cur = node.right; List<Integer> temp = new ArrayList<>(); // If no right boundary is present and there is no left subtree, skip if (cur != null && node.left == null) { return; } while (cur != null) { if (!isLeaf(cur)) { temp.add(cur.data); // Store non-leaf nodes temporarily } if (cur.right != null) { cur = cur.right; // Move to the right child } else if (cur.left != null) { cur = cur.left; // If right child is null, move to the left child } else { break; // Stop if there are no children } } // Add the right boundary nodes in reverse order for (int i = temp.size() - 1; i >= 0; i--) { result.add(temp.get(i)); } } // Checks if a node is a leaf node private static boolean isLeaf(BinaryTree.Node node) { return node.left == null && node.right == null; } // Iterative boundary traversal public static List<Integer> iterativeBoundaryTraversal(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } // Add root node if it's not a leaf node if (!isLeaf(root)) { result.add(root.data); } // Handle the left boundary BinaryTree.Node cur = root.left; if (cur == null && root.right != null) { cur = root.right; } while (cur != null) { if (!isLeaf(cur)) { result.add(cur.data); // Add non-leaf nodes to result } cur = (cur.left != null) ? cur.left : cur.right; // Prioritize left child, move to right if left is null } // Add leaf nodes addLeaves(root, result); // Handle the right boundary using a stack (reverse order) cur = root.right; Deque<Integer> stack = new LinkedList<>(); if (cur != null && root.left == null) { return result; } while (cur != null) { if (!isLeaf(cur)) { stack.push(cur.data); // Temporarily store right boundary nodes in a stack } cur = (cur.right != null) ? cur.right : cur.left; // Prioritize right child, move to left if right is null } // Add the right boundary nodes from the stack to maintain the correct order while (!stack.isEmpty()) { result.add(stack.pop()); } 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/trees/FenwickTree.java
src/main/java/com/thealgorithms/datastructures/trees/FenwickTree.java
package com.thealgorithms.datastructures.trees; public class FenwickTree { private int n; private int[] fenTree; /* Constructor which takes the size of the array as a parameter */ public FenwickTree(int n) { this.n = n; this.fenTree = new int[n + 1]; } /* A function which will add the element val at index i*/ public void update(int i, int val) { // As index starts from 0, increment the index by 1 i += 1; while (i <= n) { fenTree[i] += val; i += i & (-i); } } /* A function which will return the cumulative sum from index 1 to index i*/ public int query(int i) { // As index starts from 0, increment the index by 1 i += 1; int cumSum = 0; while (i > 0) { cumSum += fenTree[i]; i -= i & (-i); } return cumSum; } }
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/trees/BSTIterative.java
src/main/java/com/thealgorithms/datastructures/trees/BSTIterative.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; /** * * * <h1>Binary Search Tree (Iterative)</h1> * * <p> * An implementation of BST iteratively. Binary Search Tree is a binary tree * which satisfies three properties: left child is less than root node, right * child is grater than root node, both left and right child must themselves be * a BST. * * @author [Lakhan Nad](<a href="https://github.com/Lakhan-Nad">git-Lakhan Nad</a>) */ public class BSTIterative { /** * Reference for the node of BST. */ private Node root; /** * Default Constructor Initializes the root of BST with null. */ BSTIterative() { root = null; } public Node getRoot() { return root; } /** * A method to insert a new value in BST. If the given value is already * present in BST the insertion is ignored. * * @param data the value to be inserted */ public void add(int data) { Node parent = null; Node temp = this.root; int rightOrLeft = -1; /* Finds the proper place this node can * be placed in according to rules of BST. */ while (temp != null) { if (temp.data > data) { parent = temp; temp = parent.left; rightOrLeft = 0; } else if (temp.data < data) { parent = temp; temp = parent.right; rightOrLeft = 1; } else { System.out.println(data + " is already present in BST."); return; // if data already present we ignore insertion } } /* Creates a newNode with the value passed * Since this data doesn't already exists */ Node newNode = new Node(data); /* If the parent node is null * then the insertion is to be done in * root itself. */ if (parent == null) { this.root = newNode; } else { /* Check if insertion is to be made in * left or right subtree. */ if (rightOrLeft == 0) { parent.left = newNode; } else { parent.right = newNode; } } } /** * A method to delete the node in BST. If node is present it will be deleted * * @param data the value that needs to be deleted */ public void remove(int data) { Node parent = null; Node temp = this.root; int rightOrLeft = -1; /* Find the parent of the node and node itself * That is to be deleted. * parent variable store parent * temp stores node itself. * rightOrLeft use to keep track weather child * is left or right subtree */ while (temp != null) { if (temp.data == data) { break; } else if (temp.data > data) { parent = temp; temp = parent.left; rightOrLeft = 0; } else { parent = temp; temp = parent.right; rightOrLeft = 1; } } /* If temp is null than node with given value is not * present in our tree. */ if (temp != null) { Node replacement; // used to store the new values for replacing nodes if (temp.right == null && temp.left == null) { // Leaf node Case replacement = null; } else if (temp.right == null) { // Node with only right child replacement = temp.left; temp.left = null; } else if (temp.left == null) { // Node with only left child replacement = temp.right; temp.right = null; } else { /* If both left and right child are present * we replace this nodes data with * leftmost node's data in its right subtree * to maintain the balance of BST. * And then delete that node */ if (temp.right.left == null) { temp.data = temp.right.data; replacement = temp; temp.right = temp.right.right; } else { Node parent2 = temp.right; Node child = temp.right.left; while (child.left != null) { parent2 = child; child = parent2.left; } temp.data = child.data; parent2.left = child.right; replacement = temp; } } /* Change references of parent after * deleting the child. */ if (parent == null) { this.root = replacement; } else { if (rightOrLeft == 0) { parent.left = replacement; } else { parent.right = replacement; } } } } /** * A method to check if given data exists in out Binary Search Tree. * * @param data the value that needs to be searched for * @return boolean representing if the value was find */ public boolean find(int data) { Node temp = this.root; /* Check if node exists */ while (temp != null) { if (temp.data > data) { temp = temp.left; } else if (temp.data < data) { temp = temp.right; } else { /* If found return true */ System.out.println(data + " is present in the BST."); return true; } } System.out.println(data + " not found."); 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/trees/QuadTree.java
src/main/java/com/thealgorithms/datastructures/trees/QuadTree.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.List; /** * Point is a simple class that represents a point in 2D space. * * @see <a href="https://en.wikipedia.org/wiki/Point_(geometry)">Point</a> * @author <a href="https://github.com/sailok">Sailok Chinta</a> */ class Point { public double x; public double y; Point(double x, double y) { this.x = x; this.y = y; } } /** * BoundingBox is a simple class that represents a bounding box in 2D space. * * @see <a href="https://en.wikipedia.org/wiki/Bounding_box">Bounding Box</a> * @author <a href="https://github.com/sailok">Sailok Chinta</a> */ class BoundingBox { public Point center; public double halfWidth; BoundingBox(Point center, double halfWidth) { this.center = center; this.halfWidth = halfWidth; } /** * Checks if the point is inside the bounding box * * @param point The point to check * @return true if the point is inside the bounding box, false otherwise */ public boolean containsPoint(Point point) { return point.x >= center.x - halfWidth && point.x <= center.x + halfWidth && point.y >= center.y - halfWidth && point.y <= center.y + halfWidth; } /** * Checks if the bounding box intersects with the other bounding box * * @param otherBoundingBox The other bounding box * @return true if the bounding box intersects with the other bounding box, false otherwise */ public boolean intersectsBoundingBox(BoundingBox otherBoundingBox) { return otherBoundingBox.center.x - otherBoundingBox.halfWidth <= center.x + halfWidth && otherBoundingBox.center.x + otherBoundingBox.halfWidth >= center.x - halfWidth && otherBoundingBox.center.y - otherBoundingBox.halfWidth <= center.y + halfWidth && otherBoundingBox.center.y + otherBoundingBox.halfWidth >= center.y - halfWidth; } } /** * QuadTree is a tree data structure that is used to store spatial information * in an efficient way. * * This implementation is specific to Point QuadTrees * * @see <a href="https://en.wikipedia.org/wiki/Quadtree">Quad Tree</a> * @author <a href="https://github.com/sailok">Sailok Chinta</a> */ public class QuadTree { private final BoundingBox boundary; private final int capacity; private List<Point> pointList; private boolean divided; private QuadTree northWest; private QuadTree northEast; private QuadTree southWest; private QuadTree southEast; public QuadTree(BoundingBox boundary, int capacity) { this.boundary = boundary; this.capacity = capacity; this.pointList = new ArrayList<>(); this.divided = false; this.northWest = null; this.northEast = null; this.southWest = null; this.southEast = null; } /** * Inserts a point into the tree * * @param point The point to insert * @return true if the point is successfully inserted, false otherwise */ public boolean insert(Point point) { if (point == null) { return false; } // Ignore points that don't belong to this quad tree if (!boundary.containsPoint(point)) { return false; } // if the space is not already occupied, add it to the list if (pointList.size() < capacity) { pointList.add(point); return true; } // if subdivision hasn't happened, divide the tree if (!divided) { subDivide(); } // try to add the point in one of the four quadrants if (northWest.insert(point)) { return true; } if (northEast.insert(point)) { return true; } if (southWest.insert(point)) { return true; } if (southEast.insert(point)) { return true; } return false; } /** * Create four children that fully divide this quad into four quads of equal area */ private void subDivide() { double quadrantHalfWidth = boundary.halfWidth / 2; northWest = new QuadTree(new BoundingBox(new Point(boundary.center.x - quadrantHalfWidth, boundary.center.y + quadrantHalfWidth), quadrantHalfWidth), this.capacity); northEast = new QuadTree(new BoundingBox(new Point(boundary.center.x + quadrantHalfWidth, boundary.center.y + quadrantHalfWidth), quadrantHalfWidth), this.capacity); southWest = new QuadTree(new BoundingBox(new Point(boundary.center.x - quadrantHalfWidth, boundary.center.y - quadrantHalfWidth), quadrantHalfWidth), this.capacity); southEast = new QuadTree(new BoundingBox(new Point(boundary.center.x + quadrantHalfWidth, boundary.center.y - quadrantHalfWidth), quadrantHalfWidth), this.capacity); divided = true; } /** * Queries all the points that intersect with the other bounding box * * @param otherBoundingBox The other bounding box * @return List of points that intersect with the other bounding box */ public List<Point> query(BoundingBox otherBoundingBox) { List<Point> points = new ArrayList<>(); if (!boundary.intersectsBoundingBox(otherBoundingBox)) { return points; } // filter the points that intersect with the other bounding box points.addAll(pointList.stream().filter(otherBoundingBox::containsPoint).toList()); if (divided) { points.addAll(northWest.query(otherBoundingBox)); points.addAll(northEast.query(otherBoundingBox)); points.addAll(southWest.query(otherBoundingBox)); points.addAll(southEast.query(otherBoundingBox)); } return points; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
src/main/java/com/thealgorithms/datastructures/trees/nearestRightKey.java
package com.thealgorithms.datastructures.trees; import java.util.Scanner; import java.util.concurrent.ThreadLocalRandom; final class NearestRightKey { private NearestRightKey() { } public static void main(String[] args) { NRKTree root = buildTree(); Scanner sc = new Scanner(System.in); System.out.print("Enter first number: "); int inputX0 = sc.nextInt(); int toPrint = nearestRightKey(root, inputX0); System.out.println("Key: " + toPrint); sc.close(); } public static NRKTree buildTree() { int randomX = ThreadLocalRandom.current().nextInt(0, 100 + 1); NRKTree root = new NRKTree(null, null, randomX); for (int i = 0; i < 1000; i++) { randomX = ThreadLocalRandom.current().nextInt(0, 100 + 1); root = root.insertKey(root, randomX); } return root; } public static int nearestRightKey(NRKTree root, int x0) { // Check whether tree is empty if (root == null) { return 0; } else { if (root.data - x0 > 0) { // Go left int temp = nearestRightKey(root.left, x0); if (temp == 0) { return root.data; } return temp; } else { // Go right return nearestRightKey(root.right, x0); } } } } class NRKTree { public NRKTree left; public NRKTree right; public int data; NRKTree(int x) { this.left = null; this.right = null; this.data = x; } NRKTree(NRKTree right, NRKTree left, int x) { this.left = left; this.right = right; this.data = x; } public NRKTree insertKey(NRKTree current, int value) { if (current == null) { return new NRKTree(value); } if (value < current.data) { current.left = insertKey(current.left, value); } else if (value > current.data) { current.right = insertKey(current.right, value); } return current; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java
src/main/java/com/thealgorithms/datastructures/trees/PrintTopViewofTree.java
package com.thealgorithms.datastructures.trees; // Java program to print top view of Binary tree import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; // Class for a tree node class TreeNode { // Members int key; TreeNode left; TreeNode right; // Constructor TreeNode(int key) { this.key = key; left = null; right = null; } } // A class to represent a queue item. The queue is used to do Level // order traversal. Every Queue item contains node and horizontal // distance of node from root class QItem { TreeNode node; int hd; QItem(TreeNode n, int h) { node = n; hd = h; } } // Class for a Binary Tree class Tree { TreeNode root; // Constructors Tree() { root = null; } Tree(TreeNode n) { root = n; } // This method prints nodes in top view of binary tree public void printTopView() { // base case if (root == null) { return; } // Creates an empty hashset HashSet<Integer> set = new HashSet<>(); // Create a queue and add root to it Queue<QItem> queue = new LinkedList<QItem>(); queue.add(new QItem(root, 0)); // Horizontal distance of root is 0 // Standard BFS or level order traversal loop while (!queue.isEmpty()) { // Remove the front item and get its details QItem qi = queue.remove(); int hd = qi.hd; TreeNode n = qi.node; // If this is the first node at its horizontal distance, // then this node is in top view if (!set.contains(hd)) { set.add(hd); System.out.print(n.key + " "); } // Enqueue left and right children of current node if (n.left != null) { queue.add(new QItem(n.left, hd - 1)); } if (n.right != null) { queue.add(new QItem(n.right, hd + 1)); } } } } // Driver class to test above methods public final class PrintTopViewofTree { private PrintTopViewofTree() { } public static void main(String[] args) { /* Create following Binary Tree 1 / \ 2 3 \ 4 \ 5 \ 6*/ TreeNode root = new TreeNode(1); root.left = new TreeNode(2); root.right = new TreeNode(3); root.left.right = new TreeNode(4); root.left.right.right = new TreeNode(5); root.left.right.right.right = new TreeNode(6); Tree t = new Tree(root); System.out.println("Following are nodes in top view of Binary Tree"); t.printTopView(); } }
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/trees/ZigzagTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/ZigzagTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * Given a binary tree. * This code returns the zigzag level order traversal of its nodes' values. * Binary tree: * 7 * / \ * 6 3 * / \ / \ * 2 4 10 19 * Zigzag traversal: * [[7], [3, 6], [2, 4, 10, 19]] * <p> * This solution implements the breadth-first search (BFS) algorithm using a queue. * 1. The algorithm starts with a root node. This node is added to a queue. * 2. While the queue is not empty: * - each time we enter the while-loop we get queue size. Queue size refers to the number of nodes * at the current level. * - we traverse all the level nodes in 2 ways: from left to right OR from right to left * (this state is stored on `prevLevelFromLeftToRight` variable) * - if the current node has children we add them to a queue * - add level with nodes to a result. * <p> * Complexities: * O(N) - time, where N is the number of nodes in a binary tree * O(N) - space, where N is the number of nodes in a binary tree * * @author Albina Gimaletdinova on 11/01/2023 */ public final class ZigzagTraversal { private ZigzagTraversal() { } public static List<List<Integer>> traverse(BinaryTree.Node root) { if (root == null) { return List.of(); } List<List<Integer>> result = new ArrayList<>(); // create a queue Deque<BinaryTree.Node> q = new ArrayDeque<>(); q.offer(root); // start with writing nodes from left to right boolean prevLevelFromLeftToRight = false; while (!q.isEmpty()) { int nodesOnLevel = q.size(); List<Integer> level = new LinkedList<>(); // traverse all the level nodes for (int i = 0; i < nodesOnLevel; i++) { BinaryTree.Node node = q.poll(); if (prevLevelFromLeftToRight) { level.add(0, node.data); } else { level.add(node.data); } if (node.left != null) { q.offer(node.left); } if (node.right != null) { q.offer(node.right); } } // the next level node traversal will be from the other side prevLevelFromLeftToRight = !prevLevelFromLeftToRight; result.add(level); } 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/trees/CreateBinaryTreeFromInorderPreorder.java
src/main/java/com/thealgorithms/datastructures/trees/CreateBinaryTreeFromInorderPreorder.java
package com.thealgorithms.datastructures.trees; import com.thealgorithms.datastructures.trees.BinaryTree.Node; import java.util.HashMap; import java.util.Map; /** * Approach: Naive Solution: Create root node from first value present in * preorder traversal. Look for the index of root node's value in inorder * traversal. That will tell total nodes present in left subtree and right * subtree. Based on that index create left and right subtree. Complexity: Time: * O(n^2) for each node there is iteration to find index in inorder array Space: * Stack size = O(height) = O(lg(n)) * <p> * Optimized Solution: Instead of iterating over inorder array to find index of * root value, create a hashmap and find out the index of root value. * Complexity: Time: O(n) hashmap reduced iteration to find index in inorder * array Space: O(n) space taken by hashmap */ public final class CreateBinaryTreeFromInorderPreorder { private CreateBinaryTreeFromInorderPreorder() { } public static Node createTree(final Integer[] preorder, final Integer[] inorder) { if (preorder == null || inorder == null) { return null; } return createTree(preorder, inorder, 0, 0, inorder.length); } public static Node createTreeOptimized(final Integer[] preorder, final Integer[] inorder) { if (preorder == null || inorder == null) { return null; } Map<Integer, Integer> inorderMap = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { inorderMap.put(inorder[i], i); } return createTreeOptimized(preorder, inorderMap, 0, 0, inorder.length); } private static Node createTree(final Integer[] preorder, final Integer[] inorder, final int preStart, final int inStart, final int size) { if (size == 0) { return null; } Node root = new Node(preorder[preStart]); int i = inStart; while (!preorder[preStart].equals(inorder[i])) { i++; } int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; root.left = createTree(preorder, inorder, preStart + 1, inStart, leftNodesCount); root.right = createTree(preorder, inorder, preStart + leftNodesCount + 1, i + 1, rightNodesCount); return root; } private static Node createTreeOptimized(final Integer[] preorder, final Map<Integer, Integer> inorderMap, final int preStart, final int inStart, final int size) { if (size == 0) { return null; } Node root = new Node(preorder[preStart]); int i = inorderMap.get(preorder[preStart]); int leftNodesCount = i - inStart; int rightNodesCount = size - leftNodesCount - 1; root.left = createTreeOptimized(preorder, inorderMap, preStart + 1, inStart, leftNodesCount); root.right = createTreeOptimized(preorder, inorderMap, preStart + leftNodesCount + 1, i + 1, rightNodesCount); return root; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/InorderTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Deque; import java.util.List; /** * Given tree is traversed in an 'inorder' way: LEFT -> ROOT -> RIGHT. * Below are given the recursive and iterative implementations. * * Complexities: * Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree. * * Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 * \ * 6 * \ * 7 * \ * 8 * * @author Albina Gimaletdinova on 21/02/2023 */ public final class InorderTraversal { private InorderTraversal() { } public static List<Integer> recursiveInorder(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); recursiveInorder(root, result); return result; } public static List<Integer> iterativeInorder(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Deque<BinaryTree.Node> stack = new ArrayDeque<>(); while (!stack.isEmpty() || root != null) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); result.add(root.data); root = root.right; } return result; } private static void recursiveInorder(BinaryTree.Node root, List<Integer> result) { if (root == null) { return; } recursiveInorder(root.left, result); result.add(root.data); recursiveInorder(root.right, 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/trees/Treap.java
src/main/java/com/thealgorithms/datastructures/trees/Treap.java
package com.thealgorithms.datastructures.trees; import java.util.Random; /** * Treap -> Tree + Heap * Also called as cartesian tree * * @see * <a href = "https://cp-algorithms.com/data_structures/treap.html" /> */ public class Treap { public static class TreapNode { /** * TreapNode class defines the individual nodes in the Treap * * value -> holds the value of the node. * Binary Search Tree is built based on value. * * priority -> holds the priority of the node. * Heaps are maintained based on priority. * It is randomly assigned * * size -> holds the size of the subtree with current node as root * * left -> holds the left subtree * right -> holds the right subtree */ public int value; private int priority; private int size; public TreapNode left; public TreapNode right; public TreapNode(int valueParam, int priorityParam) { value = valueParam; priority = priorityParam; size = 1; left = null; right = null; } /** * updateSize -> updates the subtree size of the current node */ private void updateSize() { size = 1; if (left != null) { size += left.size; } if (right != null) { size += right.size; } } } /** * root -> holds the root node in the Treap * random -> to generate random priority for the nodes in the Treap */ private TreapNode root; private Random random = new Random(); /** * Constructors * * Treap() -> create an empty Treap * Treap(int[] nodeValues) -> add the elements given in the array to the Treap */ public Treap() { root = null; } /** * merges two Treaps left and right into a single Treap * * @param left left Treap * @param right right Treap * @return root of merged Treap */ private TreapNode merge(TreapNode left, TreapNode right) { if (left == null) { return right; } if (right == null) { return left; } if (left.priority > right.priority) { left.right = merge(left.right, right); left.updateSize(); return left; } else { right.left = merge(left, right.left); right.updateSize(); return right; } } /** * split the Treap into two Treaps where left Treap has nodes <= key and right Treap has nodes > key * * @param node root node to be split * @param key key to compare the nodes * @return TreapNode array of size 2. * TreapNode[0] contains the root of left Treap after split * TreapNode[1] contains the root of right Treap after split */ private TreapNode[] split(TreapNode node, int key) { if (node == null) { return new TreapNode[] {null, null}; } TreapNode[] result; if (node.value <= key) { result = split(node.right, key); node.right = result[0]; node.updateSize(); result[0] = node; } else { result = split(node.left, key); node.left = result[1]; node.updateSize(); result[1] = node; } return result; } /** * insert a node into the Treap * * @param value value to be inserted into the Treap * @return root of the Treap where the value is inserted */ public TreapNode insert(int value) { if (root == null) { root = new TreapNode(value, random.nextInt()); return root; } TreapNode[] splitted = split(root, value); TreapNode node = new TreapNode(value, random.nextInt()); TreapNode tempMerged = merge(splitted[0], node); tempMerged.updateSize(); TreapNode merged = merge(tempMerged, splitted[1]); merged.updateSize(); root = merged; return root; } /** * delete a value from root if present * * @param value value to be deleted from the Treap * @return root of the Treap where delete has been performed */ public TreapNode delete(int value) { root = deleteNode(root, value); return root; } private TreapNode deleteNode(TreapNode root, int value) { if (root == null) { return null; } if (value < root.value) { root.left = deleteNode(root.left, value); } else if (value > root.value) { root.right = deleteNode(root.right, value); } else { root = merge(root.left, root.right); } if (root != null) { root.updateSize(); } return root; } /** * print inorder traversal of the Treap */ public void inOrder() { System.out.print("{"); printInorder(root); System.out.print("}"); } private void printInorder(TreapNode root) { if (root == null) { return; } printInorder(root.left); System.out.print(root.value + ","); printInorder(root.right); } /** * print preOrder traversal of the Treap */ public void preOrder() { System.out.print("{"); printPreOrder(root); System.out.print("}"); } private void printPreOrder(TreapNode root) { if (root == null) { return; } System.out.print(root.value + ","); printPreOrder(root.left); printPreOrder(root.right); } /** * print postOrder traversal of the Treap */ public void postOrder() { System.out.print("{"); printPostOrder(root); System.out.print("}"); } private void printPostOrder(TreapNode root) { if (root == null) { return; } printPostOrder(root.left); printPostOrder(root.right); System.out.print(root.value + ","); } /** * Search a value in the Treap * * @param value value to be searched for * @return node containing the value * null if not found */ public TreapNode search(int value) { return searchVal(root, value); } private TreapNode searchVal(TreapNode root, int value) { if (root == null) { return null; } if (root.value == value) { return root; } else if (root.value < value) { return searchVal(root.right, value); } else { return searchVal(root.left, value); } } /** * find the lowerBound of a value in the Treap * * @param value value for which lowerBound is to be found * @return node which is the lowerBound of the value passed */ public TreapNode lowerBound(int value) { TreapNode lowerBoundNode = null; TreapNode current = root; while (current != null) { if (current.value >= value) { lowerBoundNode = current; current = current.left; } else { current = current.right; } } return lowerBoundNode; } /** * find the upperBound of a value in the Treap * * @param value value for which upperBound is to be found * @return node which is the upperBound of the value passed */ public TreapNode upperBound(int value) { TreapNode upperBoundNode = null; TreapNode current = root; while (current != null) { if (current.value > value) { upperBoundNode = current; current = current.left; } else { current = current.right; } } return upperBoundNode; } /** * returns size of the Treap */ public int size() { if (root == null) { return 0; } return root.size; } /** * returns if Treap is empty */ public boolean isEmpty() { return root == null; } /** * returns root node of the Treap */ public TreapNode getRoot() { return root; } /** * returns left node of the TreapNode */ public TreapNode getLeft(TreapNode node) { return node.left; } /** * returns the right node of the TreapNode */ public TreapNode getRight(TreapNode node) { return node.right; } /** * prints the value, priority, size of the subtree of the TreapNode, left TreapNode and right TreapNode of the node */ public String toString(TreapNode node) { return "{value : " + node.value + ", priority : " + node.priority + ", subTreeSize = " + node.size + ", left = " + node.left + ", right = " + node.right + "}"; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/datastructures/trees/Trie.java
src/main/java/com/thealgorithms/datastructures/trees/Trie.java
package com.thealgorithms.datastructures.trees; import java.util.HashMap; /** * Represents a Trie Node that stores a character and pointers to its children. * Each node has a hashmap which can point to all possible characters. * Each node also has a boolean value to indicate if it is the end of a word. */ class TrieNode { char value; HashMap<Character, TrieNode> child; boolean end; /** * Constructor to initialize a TrieNode with an empty hashmap * and set end to false. */ TrieNode(char value) { this.value = value; this.child = new HashMap<>(); this.end = false; } } /** * Trie Data structure implementation without any libraries. * <p> * The Trie (also known as a prefix tree) is a special tree-like data structure * that is used to store a dynamic set or associative array where the keys are * usually strings. It is highly efficient for prefix-based searches. * <p> * This implementation supports basic Trie operations like insertion, search, * and deletion. * <p> * Each node of the Trie represents a character and has child nodes for each * possible character. * * @author <a href="https://github.com/dheeraj92">Dheeraj Kumar Barnwal</a> * @author <a href="https://github.com/sailok">Sailok Chinta</a> */ public class Trie { private static final char ROOT_NODE_VALUE = '*'; private final TrieNode root; /** * Constructor to initialize the Trie. * The root node is created but doesn't represent any character. */ public Trie() { root = new TrieNode(ROOT_NODE_VALUE); } /** * Inserts a word into the Trie. * <p> * The method traverses the Trie from the root, character by character, and adds * nodes if necessary. It marks the last node of the word as an end node. * * @param word The word to be inserted into the Trie. */ public void insert(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null); if (node == null) { node = new TrieNode(word.charAt(i)); currentNode.child.put(word.charAt(i), node); } currentNode = node; } currentNode.end = true; } /** * Searches for a word in the Trie. * <p> * This method traverses the Trie based on the input word and checks whether * the word exists. It returns true if the word is found and its end flag is * true. * * @param word The word to search in the Trie. * @return true if the word exists in the Trie, false otherwise. */ public boolean search(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null); if (node == null) { return false; } currentNode = node; } return currentNode.end; } /** * Deletes a word from the Trie. * <p> * The method traverses the Trie to find the word and marks its end flag as * false. * It returns true if the word was successfully deleted, false if the word * wasn't found. * * @param word The word to be deleted from the Trie. * @return true if the word was found and deleted, false if it was not found. */ public boolean delete(String word) { TrieNode currentNode = root; for (int i = 0; i < word.length(); i++) { TrieNode node = currentNode.child.getOrDefault(word.charAt(i), null); if (node == null) { return false; } currentNode = node; } if (currentNode.end) { currentNode.end = false; return true; } return false; } /** * Counts the number of words in the trie *<p> * The method traverses the Trie and counts the number of words. * * @return count of words */ public int countWords() { return countWords(root); } private int countWords(TrieNode node) { if (node == null) { return 0; } int count = 0; if (node.end) { count++; } for (TrieNode child : node.child.values()) { count += countWords(child); } return count; } /** * Check if the prefix exists in the trie * * @param prefix the prefix to be checked in the Trie * @return true / false depending on the prefix if exists in the Trie */ public boolean startsWithPrefix(String prefix) { TrieNode currentNode = root; for (int i = 0; i < prefix.length(); i++) { TrieNode node = currentNode.child.getOrDefault(prefix.charAt(i), null); if (node == null) { return false; } currentNode = node; } return true; } /** * Count the number of words starting with the given prefix in the trie * * @param prefix the prefix to be checked in the Trie * @return count of words */ public int countWordsWithPrefix(String prefix) { TrieNode currentNode = root; for (int i = 0; i < prefix.length(); i++) { TrieNode node = currentNode.child.getOrDefault(prefix.charAt(i), null); if (node == null) { return 0; } currentNode = node; } return countWords(currentNode); } }
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/trees/PreOrderTraversal.java
src/main/java/com/thealgorithms/datastructures/trees/PreOrderTraversal.java
package com.thealgorithms.datastructures.trees; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * Given tree is traversed in a 'pre-order' way: ROOT -> LEFT -> RIGHT. * Below are given the recursive and iterative implementations. * * Complexities: * Recursive: O(n) - time, O(n) - space, where 'n' is the number of nodes in a tree. * * Iterative: O(n) - time, O(h) - space, where 'n' is the number of nodes in a tree * and 'h' is the height of a binary tree. * In the worst case 'h' can be O(n) if tree is completely unbalanced, for instance: * 5 * \ * 6 * \ * 7 * \ * 8 * * @author Albina Gimaletdinova on 17/02/2023 */ public final class PreOrderTraversal { private PreOrderTraversal() { } public static List<Integer> recursivePreOrder(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); recursivePreOrder(root, result); return result; } public static List<Integer> iterativePreOrder(BinaryTree.Node root) { List<Integer> result = new ArrayList<>(); if (root == null) { return result; } Deque<BinaryTree.Node> stack = new LinkedList<>(); stack.push(root); while (!stack.isEmpty()) { BinaryTree.Node node = stack.pop(); result.add(node.data); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return result; } private static void recursivePreOrder(BinaryTree.Node root, List<Integer> result) { if (root == null) { return; } result.add(root.data); recursivePreOrder(root.left, result); recursivePreOrder(root.right, 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/trees/TreeRandomNode.java
src/main/java/com/thealgorithms/datastructures/trees/TreeRandomNode.java
package com.thealgorithms.datastructures.trees; /* Author : Suraj Kumar Github : https://github.com/skmodi649 */ /* PROBLEM DESCRIPTION : There is a Binary Search Tree given, and we are supposed to find a random node in the given binary tree. */ /* ALGORITHM : Step 1: START Step 2: First create a binary tree using the steps mentioned in the first approach Step 3: Now use a method inOrder() that takes a node as input parameter to traverse through the binary tree in inorder fashion as also store the values in a ArrayList simultaneously. Step 4: Now define a method getRandom() that takes a node as input parameter, in this first call the inOrder() method to store the values in the arraylist, then find the size of the binary tree and now just generate a random number between 0 to n-1. Step 5: After generating the number display the value of the ArrayList at the generated index Step 6: STOP */ import java.util.ArrayList; // Using auxiliary array to find the random node in a given binary tree public class TreeRandomNode { private final class Node { int item; Node left; Node right; } // Using an arraylist to store the inorder traversal of the given binary tree static ArrayList<Integer> list = new ArrayList<>(); // root of Tree Node root; TreeRandomNode() { root = null; } // Now lets find the inorder traversal of the given binary tree static void inOrder(Node node) { if (node == null) { return; } // traverse the left child inOrder(node.left); list.add(node.item); // traverse the right child inOrder(node.right); } public void getRandom(Node val) { inOrder(val); // getting the count of node of the binary tree int n = list.size(); int min = 0; int max = n - 1; // Generate random int value from 0 to n-1 int b = (int) (Math.random() * (max - min + 1) + min); // displaying the value at the generated index int random = list.get(b); System.out.println("Random Node : " + random); } } /* Explanation of the Approach : (a) Form the required binary tree (b) Now use the inOrder() method to get the nodes in inOrder fashion and also store them in the given arraylist 'list' (c) Using the getRandom() method generate a random number between 0 to n-1, then get the value at the generated random number from the arraylist using get() method and finally display the result. */ /* OUTPUT : First output : Random Node : 15 Second output : Random Node : 99 */ /* Time Complexity : O(n) Auxiliary Space Complexity : O(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/datastructures/dynamicarray/DynamicArray.java
src/main/java/com/thealgorithms/datastructures/dynamicarray/DynamicArray.java
package com.thealgorithms.datastructures.dynamicarray; import java.util.Arrays; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.Consumer; import java.util.stream.Stream; import java.util.stream.StreamSupport; /** * This class implements a dynamic array, which can grow or shrink in size * as elements are added or removed. It provides an array-like interface * with methods to add, remove, and access elements, along with iterators * to traverse the elements. * * @param <E> the type of elements that this array can hold */ public class DynamicArray<E> implements Iterable<E> { private static final int DEFAULT_CAPACITY = 16; private int size; private int modCount; // Tracks structural modifications for iterator integrity private Object[] elements; /** * Constructs a new DynamicArray with the specified initial capacity. * * @param capacity the initial capacity of the array * @throws IllegalArgumentException if the specified capacity is negative */ public DynamicArray(final int capacity) { if (capacity < 0) { throw new IllegalArgumentException("Capacity cannot be negative."); } this.size = 0; this.modCount = 0; this.elements = new Object[capacity]; } /** * Constructs a new DynamicArray with a default initial capacity. */ public DynamicArray() { this(DEFAULT_CAPACITY); } /** * Adds an element to the end of the array. If the array is full, it * creates a new array with double the size to accommodate the new element. * * @param element the element to be added to the array */ public void add(final E element) { ensureCapacity(size + 1); elements[size++] = element; modCount++; // Increment modification count } /** * Places an element at the specified index, expanding capacity if necessary. * * @param index the index at which the element is to be placed * @param element the element to be inserted at the specified index * @throws IndexOutOfBoundsException if index is less than 0 or greater than or equal to the number of elements */ public void put(final int index, E element) { if (index < 0) { throw new IndexOutOfBoundsException("Index cannot be negative."); } ensureCapacity(index + 1); elements[index] = element; if (index >= size) { size = index + 1; } modCount++; // Increment modification count } /** * Retrieves the element at the specified index. * * @param index the index of the element to retrieve * @return the element at the specified index * @throws IndexOutOfBoundsException if index is less than 0 or greater than or equal to the current size */ @SuppressWarnings("unchecked") public E get(final int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } return (E) elements[index]; } /** * Removes and returns the element at the specified index. * * @param index the index of the element to be removed * @return the element that was removed from the array * @throws IndexOutOfBoundsException if index is less than 0 or greater than or equal to the current size */ public E remove(final int index) { if (index < 0 || index >= size) { throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size); } @SuppressWarnings("unchecked") E oldElement = (E) elements[index]; fastRemove(index); modCount++; // Increment modification count return oldElement; } /** * Returns the current number of elements in the array. * * @return the number of elements in the array */ public int getSize() { return size; } /** * Checks whether the array is empty. * * @return true if the array contains no elements, false otherwise */ public boolean isEmpty() { return size == 0; } /** * Returns a sequential stream with this collection as its source. * * @return a stream of the elements in the array */ public Stream<E> stream() { return StreamSupport.stream(spliterator(), false); } /** * Ensures that the array has enough capacity to hold the specified number of elements. * * @param minCapacity the minimum capacity required */ private void ensureCapacity(int minCapacity) { if (minCapacity > elements.length) { int newCapacity = Math.max(elements.length * 2, minCapacity); elements = Arrays.copyOf(elements, newCapacity); } } /** * Removes the element at the specified index without resizing the array. * This method shifts any subsequent elements to the left and clears the last element. * * @param index the index of the element to remove */ private void fastRemove(int index) { int numMoved = size - index - 1; if (numMoved > 0) { System.arraycopy(elements, index + 1, elements, index, numMoved); } elements[--size] = null; // Clear to let GC do its work } /** * Returns a string representation of the array, including only the elements that are currently stored. * * @return a string containing the elements in the array */ @Override public String toString() { return Arrays.toString(Arrays.copyOf(elements, size)); } /** * Returns an iterator over the elements in this array in proper sequence. * * @return an Iterator over the elements in the array */ @Override public Iterator<E> iterator() { return new DynamicArrayIterator(); } /** * Private iterator class for the DynamicArray. */ private final class DynamicArrayIterator implements Iterator<E> { private int cursor; private int expectedModCount; /** * Constructs a new iterator for the dynamic array. */ DynamicArrayIterator() { this.expectedModCount = modCount; } /** * Checks if there are more elements in the iteration. * * @return true if there are more elements, false otherwise */ @Override public boolean hasNext() { checkForComodification(); return cursor < size; } /** * Returns the next element in the iteration. * * @return the next element in the iteration * @throws NoSuchElementException if the iteration has no more elements */ @Override @SuppressWarnings("unchecked") public E next() { checkForComodification(); if (cursor >= size) { throw new NoSuchElementException(); } return (E) elements[cursor++]; } /** * Removes the last element returned by this iterator. * * @throws IllegalStateException if the next method has not yet been called, or the remove method has already been called after the last call to the next method */ @Override public void remove() { if (cursor <= 0) { throw new IllegalStateException("Cannot remove element before calling next()"); } checkForComodification(); DynamicArray.this.remove(--cursor); expectedModCount = modCount; } /** * Checks for concurrent modifications to the array during iteration. * * @throws ConcurrentModificationException if the array has been modified structurally */ private void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } /** * Performs the given action for each remaining element in the iterator until all elements have been processed. * * @param action the action to be performed for each element * @throws NullPointerException if the specified action is null */ @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); while (hasNext()) { action.accept(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/strings/AhoCorasick.java
src/main/java/com/thealgorithms/strings/AhoCorasick.java
/* * Aho-Corasick String Matching Algorithm Implementation * * This code implements the Aho-Corasick algorithm, which is used for efficient * string matching in a given text. It can find multiple patterns simultaneously * and records their positions in the text. * * Author: Prabhat-Kumar-42 * GitHub: https://github.com/Prabhat-Kumar-42 */ package com.thealgorithms.strings; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; public final class AhoCorasick { private AhoCorasick() { } // Trie Node Class private static class Node { // Represents a character in the trie private final Map<Character, Node> child = new HashMap<>(); // Child nodes of the current node private Node suffixLink; // Suffix link to another node in the trie private Node outputLink; // Output link to another node in the trie private int patternInd; // Index of the pattern that ends at this node Node() { this.suffixLink = null; this.outputLink = null; this.patternInd = -1; } public Map<Character, Node> getChild() { return child; } public Node getSuffixLink() { return suffixLink; } public void setSuffixLink(final Node suffixLink) { this.suffixLink = suffixLink; } public Node getOutputLink() { return outputLink; } public void setOutputLink(final Node outputLink) { this.outputLink = outputLink; } public int getPatternInd() { return patternInd; } public void setPatternInd(final int patternInd) { this.patternInd = patternInd; } } // Trie Class public static class Trie { private Node root = null; // Root node of the trie private final String[] patterns; // patterns according to which Trie is constructed public Trie(final String[] patterns) { root = new Node(); // Initialize the root of the trie this.patterns = patterns; buildTrie(); buildSuffixAndOutputLinks(); } // builds AhoCorasick Trie private void buildTrie() { // Loop through each input pattern and building Trie for (int i = 0; i < patterns.length; i++) { Node curr = root; // Start at the root of the trie for each pattern // Loop through each character in the current pattern for (int j = 0; j < patterns[i].length(); j++) { char c = patterns[i].charAt(j); // Get the current character // Check if the current node has a child for the current character if (curr.getChild().containsKey(c)) { curr = curr.getChild().get(c); // Update the current node to the child node } else { // If no child node exists, create a new one and add it to the current node's children Node nn = new Node(); curr.getChild().put(c, nn); curr = nn; // Update the current node to the new child node } } curr.setPatternInd(i); // Store the index of the pattern in the current leaf node } } private void initializeSuffixLinksForChildNodesOfTheRoot(Queue<Node> q) { for (char rc : root.getChild().keySet()) { Node childNode = root.getChild().get(rc); q.add(childNode); // Add child node to the queue childNode.setSuffixLink(root); // Set suffix link to the root } } private void buildSuffixAndOutputLinks() { root.setSuffixLink(root); // Initialize the suffix link of the root to itself Queue<Node> q = new LinkedList<>(); // Initialize a queue for BFS traversal initializeSuffixLinksForChildNodesOfTheRoot(q); while (!q.isEmpty()) { Node currentState = q.poll(); // Get the current node for processing // Iterate through child nodes of the current node for (char cc : currentState.getChild().keySet()) { Node currentChild = currentState.getChild().get(cc); // Get the child node Node parentSuffix = currentState.getSuffixLink(); // Get the parent's suffix link // Calculate the suffix link for the child based on the parent's suffix link while (!parentSuffix.getChild().containsKey(cc) && parentSuffix != root) { parentSuffix = parentSuffix.getSuffixLink(); } // Set the calculated suffix link or default to root if (parentSuffix.getChild().containsKey(cc)) { currentChild.setSuffixLink(parentSuffix.getChild().get(cc)); } else { currentChild.setSuffixLink(root); } q.add(currentChild); // Add the child node to the queue for further processing } // Establish output links for nodes to efficiently identify patterns within patterns if (currentState.getSuffixLink().getPatternInd() >= 0) { currentState.setOutputLink(currentState.getSuffixLink()); } else { currentState.setOutputLink(currentState.getSuffixLink().getOutputLink()); } } } private List<List<Integer>> initializePositionByStringIndexValue() { List<List<Integer>> positionByStringIndexValue = new ArrayList<>(patterns.length); // Stores positions where patterns are found in the text for (int i = 0; i < patterns.length; i++) { positionByStringIndexValue.add(new ArrayList<>()); } return positionByStringIndexValue; } // Searches for patterns in the input text and records their positions public List<List<Integer>> searchIn(final String text) { var positionByStringIndexValue = initializePositionByStringIndexValue(); // Initialize a list to store positions of the current pattern Node parent = root; // Start searching from the root node PatternPositionRecorder positionRecorder = new PatternPositionRecorder(positionByStringIndexValue); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); // Get the current character in the text // Check if the current node has a child for the current character if (parent.getChild().containsKey(ch)) { parent = parent.getChild().get(ch); // Update the current node to the child node positionRecorder.recordPatternPositions(parent, i); // Use the method in PatternPositionRecorder to record positions } else { // If no child node exists for the character, backtrack using suffix links while (parent != root && !parent.getChild().containsKey(ch)) { parent = parent.getSuffixLink(); } if (parent.getChild().containsKey(ch)) { i--; // Decrement i to reprocess the same character } } } setUpStartPoints(positionByStringIndexValue); return positionByStringIndexValue; } // by default positionByStringIndexValue contains end-points. This function converts those // endpoints to start points private void setUpStartPoints(List<List<Integer>> positionByStringIndexValue) { for (int i = 0; i < patterns.length; i++) { for (int j = 0; j < positionByStringIndexValue.get(i).size(); j++) { int endpoint = positionByStringIndexValue.get(i).get(j); positionByStringIndexValue.get(i).set(j, endpoint - patterns[i].length() + 1); } } } } // Class to handle pattern position recording private record PatternPositionRecorder(List<List<Integer>> positionByStringIndexValue) { // Constructor to initialize the recorder with the position list /** * Records positions for a pattern when it's found in the input text and follows * output links to record positions of other patterns. * * @param parent The current node representing a character in the pattern trie. * @param currentPosition The current position in the input text. */ public void recordPatternPositions(final Node parent, final int currentPosition) { // Check if the current node represents the end of a pattern if (parent.getPatternInd() > -1) { // Add the current position to the list of positions for the found pattern positionByStringIndexValue.get(parent.getPatternInd()).add(currentPosition); } Node outputLink = parent.getOutputLink(); // Follow output links to find and record positions of other patterns while (outputLink != null) { // Add the current position to the list of positions for the pattern linked by outputLink positionByStringIndexValue.get(outputLink.getPatternInd()).add(currentPosition); outputLink = outputLink.getOutputLink(); } } } // method to search for patterns in text public static Map<String, List<Integer>> search(final String text, final String[] patterns) { final var trie = new Trie(patterns); final var positionByStringIndexValue = trie.searchIn(text); return convert(positionByStringIndexValue, patterns); } // method for converting results to a map private static Map<String, List<Integer>> convert(final List<List<Integer>> positionByStringIndexValue, final String[] patterns) { Map<String, List<Integer>> positionByString = new HashMap<>(); for (int i = 0; i < patterns.length; i++) { String pattern = patterns[i]; List<Integer> positions = positionByStringIndexValue.get(i); positionByString.put(pattern, new ArrayList<>(positions)); } return positionByString; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/HammingDistance.java
src/main/java/com/thealgorithms/strings/HammingDistance.java
package com.thealgorithms.strings; /** * Class for calculating the Hamming distance between two strings of equal length. * <p> * The Hamming distance is the number of positions at which the corresponding symbols are different. * It is used in information theory, coding theory, and computer science. * </p> * @see <a href="https://en.wikipedia.org/wiki/Hamming_distance">Hamming distance - Wikipedia</a> */ public final class HammingDistance { private HammingDistance() { } /** * Calculates the Hamming distance between two strings of equal length. * <p> * The Hamming distance is defined only for strings of equal length. If the strings are not * of equal length, this method throws an {@code IllegalArgumentException}. * </p> * * @param s1 the first string * @param s2 the second string * @return the Hamming distance between the two strings * @throws IllegalArgumentException if the lengths of {@code s1} and {@code s2} are not equal */ public static int calculateHammingDistance(String s1, String s2) { if (s1 == null || s2 == null) { throw new IllegalArgumentException("Strings must not be null"); } if (s1.length() != s2.length()) { throw new IllegalArgumentException("String lengths must be equal"); } int distance = 0; for (int i = 0; i < s1.length(); i++) { if (s1.charAt(i) != s2.charAt(i)) { distance++; } } return distance; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/AlternativeStringArrange.java
src/main/java/com/thealgorithms/strings/AlternativeStringArrange.java
package com.thealgorithms.strings; /** * This class provides a method to arrange two strings by alternating their characters. * If one string is longer, the remaining characters of the longer string are appended at the end. * <p> * Example: * Input: "abc", "12345" * Output: "a1b2c345" * <p> * Input: "abcd", "12" * Output: "a1b2cd" * * @author Milad Sadeghi */ public final class AlternativeStringArrange { // Private constructor to prevent instantiation private AlternativeStringArrange() { } /** * Arranges two strings by alternating their characters. * * @param firstString the first input string * @param secondString the second input string * @return a new string with characters from both strings arranged alternately */ public static String arrange(String firstString, String secondString) { StringBuilder result = new StringBuilder(); int length1 = firstString.length(); int length2 = secondString.length(); int minLength = Math.min(length1, length2); for (int i = 0; i < minLength; i++) { result.append(firstString.charAt(i)); result.append(secondString.charAt(i)); } if (length1 > length2) { result.append(firstString.substring(minLength)); } else if (length2 > length1) { result.append(secondString.substring(minLength)); } 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/strings/LetterCombinationsOfPhoneNumber.java
src/main/java/com/thealgorithms/strings/LetterCombinationsOfPhoneNumber.java
package com.thealgorithms.strings; import java.util.ArrayList; import java.util.Collections; import java.util.List; public final class LetterCombinationsOfPhoneNumber { private static final char EMPTY = '\0'; // Mapping of numbers to corresponding letters on a phone keypad private static final String[] KEYPAD = new String[] {" ", String.valueOf(EMPTY), "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"}; private LetterCombinationsOfPhoneNumber() { } /** * Generates a list of all possible letter combinations that the provided * array of numbers could represent on a phone keypad. * * @param numbers an array of integers representing the phone numbers * @return a list of possible letter combinations */ public static List<String> getCombinations(int[] numbers) { if (numbers == null) { return List.of(""); } return generateCombinations(numbers, 0, new StringBuilder()); } /** * Recursive method to generate combinations of letters from the phone keypad. * * @param numbers the input array of phone numbers * @param index the current index in the numbers array being processed * @param current a StringBuilder holding the current combination of letters * @return a list of letter combinations formed from the given numbers */ private static List<String> generateCombinations(int[] numbers, int index, StringBuilder current) { // Base case: if we've processed all numbers, return the current combination if (index == numbers.length) { return new ArrayList<>(Collections.singletonList(current.toString())); } final var number = numbers[index]; if (number < 0 || number > 9) { throw new IllegalArgumentException("Input numbers must in the range [0, 9]"); } List<String> combinations = new ArrayList<>(); // Iterate over each letter and recurse to generate further combinations for (char letter : KEYPAD[number].toCharArray()) { if (letter != EMPTY) { current.append(letter); } combinations.addAll(generateCombinations(numbers, index + 1, current)); if (letter != EMPTY) { current.deleteCharAt(current.length() - 1); // Backtrack by removing the last appended letter } } return combinations; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/HorspoolSearch.java
src/main/java/com/thealgorithms/strings/HorspoolSearch.java
package com.thealgorithms.strings; import java.util.HashMap; /** * This class is not thread safe<br> * <br> * (From wikipedia) In computer science, the Boyer–Moore–Horspool algorithm or * Horspool's algorithm is an algorithm for finding substrings in strings. It * was published by Nigel Horspool in 1980. * <br> * <a href=https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore%E2%80%93Horspool_algorithm>Wikipedia * page</a><br> * <br> * * <p> * An explanation:<br> * * <p> * The Horspool algorithm is a simplification of the Boyer-Moore algorithm in * that it uses only one of the two heuristic methods for increasing the number * of characters shifted when finding a bad match in the text. This method is * usually called the "bad symbol" or "bad character" shift. The bad symbol * shift method is classified as an input enhancement method in the theory of * algorithms. Input enhancement is (from wikipedia) the principle that * processing a given input to a problem and altering it in a specific way will * increase runtime efficiency or space efficiency, or both. Both algorithms try * to match the pattern and text comparing the pattern symbols to the text's * from right to left.<br> * <br> * * <p> * In the bad symbol shift method, a table is created prior to the search, * called the "bad symbol table". The bad symbol table contains the shift values * for any symbol in the text and pattern. For these symbols, the value is the * length of the pattern, if the symbol is not in the first (length - 1) of the * pattern. Else it is the distance from its rightmost occurrence in the pattern * to the last symbol of the pattern. In practice, we only calculate the values * for the ones that exist in the first (length - 1) of the pattern.<br> * <br> * * <p> * For more details on the algorithm and the more advanced Boyer-Moore I * recommend checking out the wikipedia page and professor Anany Levitin's book: * Introduction To The Design And Analysis Of Algorithms. */ public final class HorspoolSearch { private HorspoolSearch() { } private static HashMap<Character, Integer> shiftValues; // bad symbol table private static Integer patternLength; private static int comparisons = 0; // total comparisons in the current/last search /** * Case sensitive version version of the algorithm * * @param pattern the pattern to be searched for (needle) * @param text the text being searched in (haystack) * @return -1 if not found or first index of the pattern in the text */ public static int findFirst(String pattern, String text) { return firstOccurrence(pattern, text, true); } /** * Case insensitive version version of the algorithm * * @param pattern the pattern to be searched for (needle) * @param text the text being searched in (haystack) * @return -1 if not found or first index of the pattern in the text */ public static int findFirstInsensitive(String pattern, String text) { return firstOccurrence(pattern, text, false); } /** * Utility method that returns comparisons made by last run (mainly for * tests) * * @return number of character comparisons of the last search */ public static Integer getLastComparisons() { return HorspoolSearch.comparisons; } /** * Fairly standard implementation of the Horspool algorithm. Only the index * of the last character of the pattern on the text is saved and shifted by * the appropriate amount when a mismatch is found. The algorithm stops at * the first match or when the entire text has been exhausted. * * @param pattern String to be matched in the text * @param text text String * @return index of first occurrence of the pattern in the text */ private static int firstOccurrence(String pattern, String text, boolean caseSensitive) { shiftValues = calcShiftValues(pattern); // build the bad symbol table comparisons = 0; // reset comparisons if (pattern.length() == 0) { // return failure, if pattern empty return -1; } int textIndex = pattern.length() - 1; // align pattern with text start and get index of the last character // while pattern is not out of text bounds while (textIndex < text.length()) { // try to match pattern with current part of the text starting from last character int i = pattern.length() - 1; while (i >= 0) { comparisons++; char patternChar = pattern.charAt(i); char textChar = text.charAt((textIndex + i) - (pattern.length() - 1)); if (!charEquals(patternChar, textChar, caseSensitive)) { // bad character, shift pattern textIndex += getShiftValue(text.charAt(textIndex)); break; } i--; } // check for full match if (i == -1) { return textIndex - pattern.length() + 1; } } // text exhausted, return failure return -1; } /** * Compares the argument characters * * @param c1 first character * @param c2 second character * @param caseSensitive boolean determining case sensitivity of comparison * @return truth value of the equality comparison */ private static boolean charEquals(char c1, char c2, boolean caseSensitive) { if (caseSensitive) { return c1 == c2; } return Character.toLowerCase(c1) == Character.toLowerCase(c2); } /** * Builds the bad symbol table required to run the algorithm. The method * starts from the second to last character of the pattern and moves to the * left. When it meets a new character, it is by definition its rightmost * occurrence and therefore puts the distance from the current index to the * index of the last character into the table. If the character is already * in the table, then it is not a rightmost occurrence, so it continues. * * @param pattern basis for the bad symbol table * @return the bad symbol table */ private static HashMap<Character, Integer> calcShiftValues(String pattern) { patternLength = pattern.length(); HashMap<Character, Integer> table = new HashMap<>(); for (int i = pattern.length() - 2; i >= 0; i--) { // length - 2 is the index of the second to last character char c = pattern.charAt(i); int finalI = i; table.computeIfAbsent(c, k -> pattern.length() - 1 - finalI); } return table; } /** * Helper function that uses the bad symbol shift table to return the * appropriate shift value for a given character * * @param c character * @return shift value that corresponds to the character argument */ private static Integer getShiftValue(char c) { if (shiftValues.get(c) != null) { return shiftValues.get(c); } else { return patternLength; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/WordLadder.java
src/main/java/com/thealgorithms/strings/WordLadder.java
package com.thealgorithms.strings; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; /** * Class to find the shortest transformation sequence from a beginWord to an endWord using a dictionary of words. * A transformation sequence is a sequence of words where each adjacent pair differs by exactly one letter. */ public final class WordLadder { private WordLadder() { } /** * Finds the shortest transformation sequence from beginWord to endWord. * * @param beginWord the starting word of the transformation sequence * @param endWord the target word of the transformation sequence * @param wordList a list of words that can be used in the transformation sequence * @return the number of words in the shortest transformation sequence, or 0 if no such sequence exists */ public static int ladderLength(String beginWord, String endWord, Collection<String> wordList) { Set<String> wordSet = new HashSet<>(wordList); if (!wordSet.contains(endWord)) { return 0; } Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); int level = 1; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String currentWord = queue.poll(); char[] currentWordChars = currentWord.toCharArray(); for (int j = 0; j < currentWordChars.length; j++) { char originalChar = currentWordChars[j]; for (char c = 'a'; c <= 'z'; c++) { if (currentWordChars[j] == c) { continue; } currentWordChars[j] = c; String newWord = new String(currentWordChars); if (newWord.equals(endWord)) { return level + 1; } if (wordSet.remove(newWord)) { queue.offer(newWord); } } currentWordChars[j] = originalChar; } } level++; } return 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/strings/CheckVowels.java
src/main/java/com/thealgorithms/strings/CheckVowels.java
package com.thealgorithms.strings; import java.util.Set; /** * Vowel Count is a system whereby character strings are placed in order based * on the position of the characters in the conventional ordering of an * alphabet. Wikipedia: https://en.wikipedia.org/wiki/Alphabetical_order */ public final class CheckVowels { private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u'); private CheckVowels() { } /** * Checks if a string contains any vowels. * * @param input a string to check * @return {@code true} if the given string contains at least one vowel, otherwise {@code false} */ public static boolean hasVowels(String input) { if (input == null || input.isEmpty()) { return false; } for (char c : input.toLowerCase().toCharArray()) { if (VOWELS.contains(c)) { 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/strings/KMP.java
src/main/java/com/thealgorithms/strings/KMP.java
package com.thealgorithms.strings; /** * Implementation of Knuth–Morris–Pratt algorithm Usage: see the main function * for an example */ public final class KMP { private KMP() { } // a working example public static void main(String[] args) { final String haystack = "AAAAABAAABA"; // This is the full string final String needle = "AAAA"; // This is the substring that we want to find kmpMatcher(haystack, needle); } // find the starting index in string haystack[] that matches the search word P[] public static void kmpMatcher(final String haystack, final String needle) { final int m = haystack.length(); final int n = needle.length(); final int[] pi = computePrefixFunction(needle); int q = 0; for (int i = 0; i < m; i++) { while (q > 0 && haystack.charAt(i) != needle.charAt(q)) { q = pi[q - 1]; } if (haystack.charAt(i) == needle.charAt(q)) { q++; } if (q == n) { System.out.println("Pattern starts: " + (i + 1 - n)); q = pi[q - 1]; } } } // return the prefix function private static int[] computePrefixFunction(final String p) { final int n = p.length(); final int[] pi = new int[n]; pi[0] = 0; int q = 0; for (int i = 1; i < n; i++) { while (q > 0 && p.charAt(q) != p.charAt(i)) { q = pi[q - 1]; } if (p.charAt(q) == p.charAt(i)) { q++; } pi[i] = q; } return pi; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/ReverseWordsInString.java
src/main/java/com/thealgorithms/strings/ReverseWordsInString.java
package com.thealgorithms.strings; import java.util.Arrays; import java.util.Collections; public final class ReverseWordsInString { private ReverseWordsInString() { } /** * @brief Reverses words in the input string * @param s the input string * @return A string created by reversing the order of the words in {@code s} */ public static String reverseWordsInString(final String s) { var words = s.trim().split("\\s+"); Collections.reverse(Arrays.asList(words)); return String.join(" ", words); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java
src/main/java/com/thealgorithms/strings/RemoveDuplicateFromString.java
package com.thealgorithms.strings; /** * @author Varun Upadhyay (https://github.com/varunu28) */ public final class RemoveDuplicateFromString { private RemoveDuplicateFromString() { } /** * Removes duplicate characters from the given string. * * @param input The input string from which duplicate characters need to be removed. * @return A string containing only unique characters from the input, in their original order. */ public static String removeDuplicate(String input) { if (input == null || input.isEmpty()) { return input; } StringBuilder uniqueChars = new StringBuilder(); for (char c : input.toCharArray()) { if (uniqueChars.indexOf(String.valueOf(c)) == -1) { uniqueChars.append(c); // Append character if it's not already in the StringBuilder } } return uniqueChars.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/strings/StringCompression.java
src/main/java/com/thealgorithms/strings/StringCompression.java
package com.thealgorithms.strings; /** * References : https://en.wikipedia.org/wiki/Run-length_encoding * String compression algorithm deals with encoding the string, that is, shortening the size of the string * @author Swarga-codes (https://github.com/Swarga-codes) */ public final class StringCompression { private StringCompression() { } /** * Returns the compressed or encoded string * * @param input character array that contains the group of characters to be encoded * @return the compressed character array as string */ public static String compress(String input) { // Keeping the count as 1 since every element present will have at least a count of 1 int count = 1; String compressedString = ""; // Base condition to check whether the array is of size 1, if it is then we return the array if (input.length() == 1) { return "" + input.charAt(0); } // If the array has a length greater than 1 we move into this loop for (int i = 0; i < input.length() - 1; i++) { // here we check for similarity of the adjacent elements and change the count accordingly if (input.charAt(i) == input.charAt(i + 1)) { count = count + 1; } if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { compressedString = appendCount(compressedString, count, input.charAt(i)); break; } else if (input.charAt(i) != input.charAt(i + 1)) { if ((i + 1) == input.length() - 1) { compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i + 1); break; } else { compressedString = appendCount(compressedString, count, input.charAt(i)); count = 1; } } } return compressedString; } /** * @param res the resulting string * @param count current count * @param ch the character at a particular index * @return the res string appended with the count */ public static String appendCount(String res, int count, char ch) { if (count > 1) { res += ch + "" + count; } else { res += ch + ""; } return res; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Anagrams.java
src/main/java/com/thealgorithms/strings/Anagrams.java
package com.thealgorithms.strings; import java.util.Arrays; import java.util.HashMap; /** * An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, * typically using all the original letters exactly once.[1] * For example, the word anagram itself can be rearranged into nag a ram, * also the word binary into brainy and the word adobe into abode. * Reference from https://en.wikipedia.org/wiki/Anagram */ public final class Anagrams { private Anagrams() { } /** * Checks if two strings are anagrams by sorting the characters and comparing them. * Time Complexity: O(n log n) * Space Complexity: O(n) * * @param s the first string * @param t the second string * @return true if the strings are anagrams, false otherwise */ public static boolean areAnagramsBySorting(String s, String t) { s = s.toLowerCase().replaceAll("[^a-z]", ""); t = t.toLowerCase().replaceAll("[^a-z]", ""); if (s.length() != t.length()) { return false; } char[] c = s.toCharArray(); char[] d = t.toCharArray(); Arrays.sort(c); Arrays.sort(d); return Arrays.equals(c, d); } /** * Checks if two strings are anagrams by counting the frequency of each character. * Time Complexity: O(n) * Space Complexity: O(1) * * @param s the first string * @param t the second string * @return true if the strings are anagrams, false otherwise */ public static boolean areAnagramsByCountingChars(String s, String t) { s = s.toLowerCase().replaceAll("[^a-z]", ""); t = t.toLowerCase().replaceAll("[^a-z]", ""); int[] dict = new int[128]; for (char ch : s.toCharArray()) { dict[ch]++; } for (char ch : t.toCharArray()) { dict[ch]--; } for (int e : dict) { if (e != 0) { return false; } } return true; } /** * Checks if two strings are anagrams by counting the frequency of each character * using a single array. * Time Complexity: O(n) * Space Complexity: O(1) * * @param s the first string * @param t the second string * @return true if the strings are anagrams, false otherwise */ public static boolean areAnagramsByCountingCharsSingleArray(String s, String t) { s = s.toLowerCase().replaceAll("[^a-z]", ""); t = t.toLowerCase().replaceAll("[^a-z]", ""); if (s.length() != t.length()) { return false; } int[] charCount = new int[26]; for (int i = 0; i < s.length(); i++) { charCount[s.charAt(i) - 'a']++; charCount[t.charAt(i) - 'a']--; } for (int count : charCount) { if (count != 0) { return false; } } return true; } /** * Checks if two strings are anagrams using a HashMap to store character frequencies. * Time Complexity: O(n) * Space Complexity: O(n) * * @param s the first string * @param t the second string * @return true if the strings are anagrams, false otherwise */ public static boolean areAnagramsUsingHashMap(String s, String t) { s = s.toLowerCase().replaceAll("[^a-z]", ""); t = t.toLowerCase().replaceAll("[^a-z]", ""); if (s.length() != t.length()) { return false; } HashMap<Character, Integer> charCountMap = new HashMap<>(); for (char c : s.toCharArray()) { charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1); } for (char c : t.toCharArray()) { if (!charCountMap.containsKey(c) || charCountMap.get(c) == 0) { return false; } charCountMap.put(c, charCountMap.get(c) - 1); } return charCountMap.values().stream().allMatch(count -> count == 0); } /** * Checks if two strings are anagrams using an array to track character frequencies. * This approach optimizes space complexity by using only one array. * Time Complexity: O(n) * Space Complexity: O(1) * * @param s the first string * @param t the second string * @return true if the strings are anagrams, false otherwise */ public static boolean areAnagramsBySingleFreqArray(String s, String t) { s = s.toLowerCase().replaceAll("[^a-z]", ""); t = t.toLowerCase().replaceAll("[^a-z]", ""); if (s.length() != t.length()) { return false; } int[] freq = new int[26]; for (int i = 0; i < s.length(); i++) { freq[s.charAt(i) - 'a']++; freq[t.charAt(i) - 'a']--; } for (int count : freq) { if (count != 0) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/StringMatchFiniteAutomata.java
src/main/java/com/thealgorithms/strings/StringMatchFiniteAutomata.java
package com.thealgorithms.strings; import java.util.Set; import java.util.TreeSet; /** * A class to perform string matching using <a href="https://en.wikipedia.org/wiki/Finite-state_machine">finite automata</a>. * * @author <a href="https://github.com/prateekKrOraon">Prateek Kumar Oraon</a> */ public final class StringMatchFiniteAutomata { // Constants private static final int CHARS = Character.MAX_VALUE + 1; // Total number of characters in the input alphabet // Private constructor to prevent instantiation private StringMatchFiniteAutomata() { } /** * Searches for the pattern in the given text using finite automata. * * @param text The text to search within. * @param pattern The pattern to search for. */ public static Set<Integer> searchPattern(final String text, final String pattern) { final var stateTransitionTable = computeStateTransitionTable(pattern); FiniteAutomata finiteAutomata = new FiniteAutomata(stateTransitionTable); Set<Integer> indexFound = new TreeSet<>(); for (int i = 0; i < text.length(); i++) { finiteAutomata.consume(text.charAt(i)); if (finiteAutomata.getState() == pattern.length()) { indexFound.add(i - pattern.length() + 1); } } return indexFound; } /** * Computes the finite automata table for the given pattern. * * @param pattern The pattern to preprocess. * @return The state transition table. */ private static int[][] computeStateTransitionTable(final String pattern) { final int patternLength = pattern.length(); int[][] stateTransitionTable = new int[patternLength + 1][CHARS]; for (int state = 0; state <= patternLength; ++state) { for (int x = 0; x < CHARS; ++x) { stateTransitionTable[state][x] = getNextState(pattern, patternLength, state, x); } } return stateTransitionTable; } /** * Gets the next state for the finite automata. * * @param pattern The pattern being matched. * @param patternLength The length of the pattern. * @param state The current state. * @param x The current character from the input alphabet. * @return The next state. */ private static int getNextState(final String pattern, final int patternLength, final int state, final int x) { // If the current state is less than the length of the pattern // and the character matches the pattern character, go to the next state if (state < patternLength && x == pattern.charAt(state)) { return state + 1; } // Check for the highest prefix which is also a suffix for (int ns = state; ns > 0; ns--) { if (pattern.charAt(ns - 1) == x) { boolean match = true; for (int i = 0; i < ns - 1; i++) { if (pattern.charAt(i) != pattern.charAt(state - ns + i + 1)) { match = false; break; } } if (match) { return ns; } } } // If no prefix which is also a suffix is found, return 0 return 0; } /** * A class representing the finite automata for pattern matching. */ private static final class FiniteAutomata { private int state = 0; private final int[][] stateTransitionTable; private FiniteAutomata(int[][] stateTransitionTable) { this.stateTransitionTable = stateTransitionTable; } /** * Consumes an input character and transitions to the next state. * * @param input The input character. */ private void consume(final char input) { state = stateTransitionTable[state][input]; } /** * Gets the current state of the finite automata. * * @return The current state. */ private int getState() { return state; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/Palindrome.java
src/main/java/com/thealgorithms/strings/Palindrome.java
package com.thealgorithms.strings; /** * Wikipedia: https://en.wikipedia.org/wiki/Palindrome */ final class Palindrome { private Palindrome() { } /** * Check if a string is palindrome string or not using String Builder * * @param s a string to check * @return {@code true} if given string is palindrome, otherwise * {@code false} */ public static boolean isPalindrome(String s) { return ((s == null || s.length() <= 1) || s.equals(new StringBuilder(s).reverse().toString())); } /** * Check if a string is palindrome string or not using recursion * * @param s a string to check * @return {@code true} if given string is palindrome, otherwise * {@code false} */ public static boolean isPalindromeRecursion(String s) { if (s == null || s.length() <= 1) { return true; } if (s.charAt(0) != s.charAt(s.length() - 1)) { return false; } return isPalindromeRecursion(s.substring(1, s.length() - 1)); } /** * Check if a string is palindrome string or not using two pointer technique * * @param s a string to check * @return {@code true} if given string is palindrome, otherwise * {@code false} */ public static boolean isPalindromeTwoPointer(String s) { if (s == null || s.length() <= 1) { return true; } for (int i = 0, j = s.length() - 1; i < j; ++i, --j) { if (s.charAt(i) != s.charAt(j)) { return false; } } return true; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/strings/LongestCommonPrefix.java
src/main/java/com/thealgorithms/strings/LongestCommonPrefix.java
package com.thealgorithms.strings; import java.util.Arrays; /** * Utility class for string operations. * <p> * This class provides a method to find the longest common prefix (LCP) * among an array of strings. * </p> * * @see <a href="https://en.wikipedia.org/wiki/Longest_common_prefix">Longest Common Prefix - Wikipedia</a> */ public final class LongestCommonPrefix { private LongestCommonPrefix() { } /** * Finds the longest common prefix among a list of strings using lexicographical sorting. * The prefix is common to the first and last elements after sorting the array. * * @param strs array of input strings * @return the longest common prefix, or empty string if none exists */ public static String longestCommonPrefix(String[] strs) { if (strs == null || strs.length == 0) { return ""; } Arrays.sort(strs); String first = strs[0]; String last = strs[strs.length - 1]; int index = 0; while (index < first.length() && index < last.length() && first.charAt(index) == last.charAt(index)) { index++; } return first.substring(0, 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/strings/Manacher.java
src/main/java/com/thealgorithms/strings/Manacher.java
package com.thealgorithms.strings; /** * Wikipedia: https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher's_algorithm */ public final class Manacher { private Manacher() { } /** * Finds the longest palindromic substring using Manacher's Algorithm * * @param s The input string * @return The longest palindromic substring in {@code s} */ public static String longestPalindrome(String s) { final String processedString = preprocess(s); int[] palindromeLengths = new int[processedString.length()]; int center = 0; int rightBoundary = 0; int maxLen = 0; int centerIndex = 0; for (int i = 1; i < processedString.length() - 1; i++) { int mirror = 2 * center - i; if (i < rightBoundary) { palindromeLengths[i] = Math.min(rightBoundary - i, palindromeLengths[mirror]); } while (processedString.charAt(i + 1 + palindromeLengths[i]) == processedString.charAt(i - 1 - palindromeLengths[i])) { palindromeLengths[i]++; } if (i + palindromeLengths[i] > rightBoundary) { center = i; rightBoundary = i + palindromeLengths[i]; } if (palindromeLengths[i] > maxLen) { maxLen = palindromeLengths[i]; centerIndex = i; } } final int start = (centerIndex - maxLen) / 2; return s.substring(start, start + maxLen); } /** * Preprocesses the input string by inserting a special character ('#') between each character * and adding '^' at the start and '$' at the end to avoid boundary conditions. * * @param s The original string * @return The preprocessed string with additional characters */ private static String preprocess(String s) { if (s.isEmpty()) { return "^$"; } StringBuilder sb = new StringBuilder("^"); for (char c : s.toCharArray()) { sb.append('#').append(c); } sb.append("#$"); return sb.toString(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false