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/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java
src/test/java/com/thealgorithms/others/QueueUsingTwoStacksTest.java
package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.EmptyStackException; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class QueueUsingTwoStacksTest { private QueueUsingTwoStacks queue; @BeforeEach void setUp() { queue = new QueueUsingTwoStacks(); } @Test void testIsEmptyInitially() { assertTrue(queue.isEmpty(), "Queue should be empty initially"); } @Test void testInsertSingleElement() { queue.insert(1); assertFalse(queue.isEmpty(), "Queue should not be empty after inserting an element"); assertEquals(1, queue.peekFront(), "The front element should be the inserted element"); } @Test void testRemoveSingleElement() { queue.insert(1); assertEquals(1, queue.remove(), "Removing should return the first inserted element"); assertTrue(queue.isEmpty(), "Queue should be empty after removing the only element"); } @Test void testRemoveMultipleElements() { queue.insert(1); queue.insert(2); queue.insert(3); assertEquals(1, queue.remove(), "First removed element should be the first inserted element"); assertEquals(2, queue.remove(), "Second removed element should be the second inserted element"); assertEquals(3, queue.remove(), "Third removed element should be the third inserted element"); assertTrue(queue.isEmpty(), "Queue should be empty after removing all elements"); } @Test void testPeekFrontWithMultipleElements() { queue.insert(1); queue.insert(2); queue.insert(3); assertEquals(1, queue.peekFront(), "The front element should be the first inserted element"); } @Test void testPeekBackWithMultipleElements() { queue.insert(1); queue.insert(2); queue.insert(3); assertEquals(3, queue.peekBack(), "The back element should be the last inserted element"); } @Test void testPeekFrontAfterRemovals() { queue.insert(1); queue.insert(2); queue.insert(3); queue.remove(); assertEquals(2, queue.peekFront(), "After removing one element, the front should be the second element"); } @Test void testIsEmptyAfterRemovals() { queue.insert(1); queue.insert(2); queue.remove(); queue.remove(); assertTrue(queue.isEmpty(), "Queue should be empty after removing all elements"); } @Test void testRemoveFromEmptyQueue() { org.junit.jupiter.api.Assertions.assertThrows(EmptyStackException.class, queue::remove, "Removing from an empty queue should throw an exception"); } @Test void testPeekFrontFromEmptyQueue() { org.junit.jupiter.api.Assertions.assertThrows(EmptyStackException.class, queue::peekFront, "Peeking front from an empty queue should throw an exception"); } @Test void testPeekBackFromEmptyQueue() { org.junit.jupiter.api.Assertions.assertThrows(EmptyStackException.class, queue::peekBack, "Peeking back from an empty queue should throw an exception"); } @Test void testIsInStackEmptyInitially() { assertTrue(queue.isInStackEmpty(), "inStack should be empty initially"); } @Test void testIsOutStackEmptyInitially() { assertTrue(queue.isOutStackEmpty(), "outStack should be empty initially"); } @Test void testIsInStackEmptyAfterInsertion() { queue.insert(1); assertFalse(queue.isInStackEmpty(), "inStack should not be empty after an insertion"); } @Test void testIsOutStackEmptyAfterInsertion() { queue.insert(1); assertTrue(queue.isOutStackEmpty(), "outStack should still be empty after an insertion"); } @Test void testIsOutStackEmptyAfterRemoval() { queue.insert(1); queue.remove(); assertTrue(queue.isOutStackEmpty(), "outStack should be empty after removing the only element"); } @Test void testIsInStackEmptyAfterMultipleRemovals() { queue.insert(1); queue.insert(2); queue.remove(); queue.remove(); assertTrue(queue.isInStackEmpty(), "inStack should be empty after removing all elements"); } @Test void testIsOutStackEmptyAfterMultipleRemovals() { queue.insert(1); queue.insert(2); queue.remove(); queue.remove(); assertTrue(queue.isOutStackEmpty(), "outStack should be empty after removing all elements"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/TwoPointersTest.java
src/test/java/com/thealgorithms/others/TwoPointersTest.java
package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class TwoPointersTest { @Test void testPositivePairExists() { int[] arr = {2, 6, 9, 22, 121}; int key = 28; assertTrue(TwoPointers.isPairedSum(arr, key)); } @Test void testNegativePairExists() { int[] arr = {-12, -1, 0, 8, 12}; int key = 0; assertTrue(TwoPointers.isPairedSum(arr, key)); } @Test void testPairDoesNotExist() { int[] arr = {0, 12, 12, 35, 152}; int key = 13; assertFalse(TwoPointers.isPairedSum(arr, key)); } @Test void testNegativeSumPair() { int[] arr = {-10, -3, 1, 2, 5, 9}; int key = -8; assertTrue(TwoPointers.isPairedSum(arr, key)); } @Test void testPairDoesNotExistWithPositiveSum() { int[] arr = {1, 2, 3, 4, 5}; int key = 10; assertFalse(TwoPointers.isPairedSum(arr, key)); } @Test void testEmptyArray() { int[] arr = {}; int key = 5; assertFalse(TwoPointers.isPairedSum(arr, key)); } @Test void testSingleElementArray() { int[] arr = {5}; int key = 5; assertFalse(TwoPointers.isPairedSum(arr, key)); } @Test void testArrayWithDuplicateElements() { int[] arr = {1, 1, 3, 5, 5}; int key = 6; assertTrue(TwoPointers.isPairedSum(arr, key)); } @Test void testPairExistsAtEdges() { int[] arr = {1, 3, 4, 7, 8}; int key = 9; assertTrue(TwoPointers.isPairedSum(arr, key)); } @Test void isPairedSumShouldThrowExceptionWhenArrayIsNull() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> TwoPointers.isPairedSum(null, 10)); assertEquals("Input array must not be null.", exception.getMessage()); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java
src/test/java/com/thealgorithms/others/NewManShanksPrimeTest.java
package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertTrue; import com.thealgorithms.dynamicprogramming.NewManShanksPrime; import org.junit.jupiter.api.Test; public class NewManShanksPrimeTest { @Test void testOne() { assertTrue(NewManShanksPrime.nthManShanksPrime(1, 1)); } @Test void testTwo() { assertTrue(NewManShanksPrime.nthManShanksPrime(2, 3)); } @Test void testThree() { assertTrue(NewManShanksPrime.nthManShanksPrime(3, 7)); } @Test void testFour() { assertTrue(NewManShanksPrime.nthManShanksPrime(4, 17)); } @Test void testFive() { assertTrue(NewManShanksPrime.nthManShanksPrime(5, 41)); } @Test void testSix() { assertTrue(NewManShanksPrime.nthManShanksPrime(6, 99)); } @Test void testSeven() { assertTrue(NewManShanksPrime.nthManShanksPrime(7, 239)); } @Test void testEight() { assertTrue(NewManShanksPrime.nthManShanksPrime(8, 577)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/IterativeFloodFillTest.java
src/test/java/com/thealgorithms/others/IterativeFloodFillTest.java
package com.thealgorithms.others; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import org.junit.jupiter.api.Test; class IterativeFloodFillTest { @Test void testForEmptyImage() { int[][] image = {}; int[][] expected = {}; IterativeFloodFill.floodFill(image, 4, 5, 3, 2); assertArrayEquals(expected, image); } @Test void testForSingleElementImage() { int[][] image = {{1}}; int[][] expected = {{3}}; IterativeFloodFill.floodFill(image, 0, 0, 3, 1); assertArrayEquals(expected, image); } @Test void testForEmptyRow() { int[][] image = {{}}; int[][] expected = {{}}; IterativeFloodFill.floodFill(image, 4, 5, 3, 2); assertArrayEquals(expected, image); } @Test void testForImageOne() { int[][] image = { {0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 1, 1, 5, 0, 0}, {0, 3, 1, 1, 5, 5, 3}, {0, 3, 5, 5, 1, 1, 3}, {0, 0, 0, 5, 1, 1, 3}, {0, 0, 0, 3, 3, 3, 3}, }; int[][] expected = { {0, 0, 0, 0, 0, 0, 0}, {0, 3, 3, 3, 3, 0, 0}, {0, 3, 2, 2, 5, 0, 0}, {0, 3, 2, 2, 5, 5, 3}, {0, 3, 5, 5, 2, 2, 3}, {0, 0, 0, 5, 2, 2, 3}, {0, 0, 0, 3, 3, 3, 3}, }; IterativeFloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } @Test void testForImageTwo() { int[][] image = { {0, 0, 1, 1, 0, 0, 0}, {1, 1, 3, 3, 3, 0, 0}, {1, 3, 1, 1, 5, 0, 0}, {0, 3, 1, 1, 5, 5, 3}, {0, 3, 5, 5, 1, 1, 3}, {0, 0, 0, 5, 1, 1, 3}, {0, 0, 0, 1, 3, 1, 3}, }; int[][] expected = { {0, 0, 2, 2, 0, 0, 0}, {2, 2, 3, 3, 3, 0, 0}, {2, 3, 2, 2, 5, 0, 0}, {0, 3, 2, 2, 5, 5, 3}, {0, 3, 5, 5, 2, 2, 3}, {0, 0, 0, 5, 2, 2, 3}, {0, 0, 0, 2, 3, 2, 3}, }; IterativeFloodFill.floodFill(image, 2, 2, 2, 1); assertArrayEquals(expected, image); } @Test void testForImageThree() { int[][] image = { {1, 1, 2, 3, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1}, {1, 1, 1, 0, 3, 1, 2}, }; int[][] expected = { {4, 4, 2, 3, 4, 4, 4}, {4, 0, 0, 4, 0, 0, 4}, {4, 4, 4, 0, 3, 4, 2}, }; IterativeFloodFill.floodFill(image, 0, 1, 4, 1); assertArrayEquals(expected, image); } @Test void testForSameNewAndOldColor() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; IterativeFloodFill.floodFill(image, 0, 1, 1, 1); assertArrayEquals(expected, image); } @Test void testForBigImage() { int[][] image = new int[100][100]; assertDoesNotThrow(() -> IterativeFloodFill.floodFill(image, 0, 0, 1, 0)); } @Test void testForBelowZeroX() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; IterativeFloodFill.floodFill(image, -1, 1, 1, 0); assertArrayEquals(expected, image); } @Test void testForBelowZeroY() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; IterativeFloodFill.floodFill(image, 1, -1, 1, 0); assertArrayEquals(expected, image); } @Test void testForAboveBoundaryX() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; IterativeFloodFill.floodFill(image, 100, 1, 1, 0); assertArrayEquals(expected, image); } @Test void testForAboveBoundaryY() { int[][] image = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; int[][] expected = {{1, 1, 2}, {1, 0, 0}, {1, 1, 1}}; IterativeFloodFill.floodFill(image, 1, 100, 1, 0); assertArrayEquals(expected, image); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
src/test/java/com/thealgorithms/others/LowestBasePalindromeTest.java
package com.thealgorithms.others; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; /** * Comprehensive test suite for {@link LowestBasePalindrome}. * Tests all public methods including edge cases and exception handling. * * @author TheAlgorithms Contributors */ public class LowestBasePalindromeTest { @ParameterizedTest @MethodSource("provideListsForIsPalindromicPositive") public void testIsPalindromicPositive(List<Integer> list) { Assertions.assertTrue(LowestBasePalindrome.isPalindromic(list)); } @ParameterizedTest @MethodSource("provideListsForIsPalindromicNegative") public void testIsPalindromicNegative(List<Integer> list) { Assertions.assertFalse(LowestBasePalindrome.isPalindromic(list)); } @ParameterizedTest @MethodSource("provideNumbersAndBasesForIsPalindromicInBasePositive") public void testIsPalindromicInBasePositive(int number, int base) { Assertions.assertTrue(LowestBasePalindrome.isPalindromicInBase(number, base)); } @ParameterizedTest @MethodSource("provideNumbersAndBasesForIsPalindromicInBaseNegative") public void testIsPalindromicInBaseNegative(int number, int base) { Assertions.assertFalse(LowestBasePalindrome.isPalindromicInBase(number, base)); } @ParameterizedTest @MethodSource("provideNumbersAndBasesForExceptions") public void testIsPalindromicInBaseThrowsException(int number, int base) { Assertions.assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.isPalindromicInBase(number, base)); } @ParameterizedTest @MethodSource("provideNumbersForLowestBasePalindrome") public void testLowestBasePalindrome(int number, int expectedBase) { Assertions.assertEquals(expectedBase, LowestBasePalindrome.lowestBasePalindrome(number)); } @ParameterizedTest @MethodSource("provideNumbersForComputeDigitsInBase") public void testComputeDigitsInBase(int number, int base, List<Integer> expectedDigits) { Assertions.assertEquals(expectedDigits, LowestBasePalindrome.computeDigitsInBase(number, base)); } @ParameterizedTest @MethodSource("provideInvalidNumbersForComputeDigits") public void testComputeDigitsInBaseThrowsExceptionForNegativeNumber(int number, int base) { Assertions.assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.computeDigitsInBase(number, base)); } @ParameterizedTest @MethodSource("provideInvalidBasesForComputeDigits") public void testComputeDigitsInBaseThrowsExceptionForInvalidBase(int number, int base) { Assertions.assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.computeDigitsInBase(number, base)); } @ParameterizedTest @MethodSource("provideNegativeNumbersForLowestBasePalindrome") public void testLowestBasePalindromeThrowsExceptionForNegativeNumber(int number) { Assertions.assertThrows(IllegalArgumentException.class, () -> LowestBasePalindrome.lowestBasePalindrome(number)); } private static Stream<Arguments> provideListsForIsPalindromicPositive() { return Stream.of(Arguments.of(new ArrayList<>()), Arguments.of(new ArrayList<>(List.of(1))), Arguments.of(new ArrayList<>(Arrays.asList(1, 1))), Arguments.of(new ArrayList<>(Arrays.asList(1, 2, 1))), Arguments.of(new ArrayList<>(Arrays.asList(1, 2, 2, 1)))); } private static Stream<Arguments> provideListsForIsPalindromicNegative() { return Stream.of(Arguments.of(new ArrayList<>(Arrays.asList(1, 2))), Arguments.of(new ArrayList<>(Arrays.asList(1, 2, 1, 1)))); } private static Stream<Arguments> provideNumbersAndBasesForIsPalindromicInBasePositive() { return Stream.of(Arguments.of(101, 10), Arguments.of(1, 190), Arguments.of(0, 11), Arguments.of(10101, 10), Arguments.of(23, 22)); } private static Stream<Arguments> provideNumbersAndBasesForIsPalindromicInBaseNegative() { return Stream.of(Arguments.of(1010, 10), Arguments.of(123, 10)); } private static Stream<Arguments> provideNumbersAndBasesForExceptions() { return Stream.of(Arguments.of(-1, 5), Arguments.of(10, 1)); } private static Stream<Arguments> provideNumbersForLowestBasePalindrome() { return Stream.of(Arguments.of(0, 2), Arguments.of(1, 2), Arguments.of(2, 3), Arguments.of(3, 2), Arguments.of(10, 3), Arguments.of(11, 10), Arguments.of(15, 2), Arguments.of(39, 12), Arguments.of(44, 10), Arguments.of(58, 28), Arguments.of(69, 22), Arguments.of(79, 78), Arguments.of(87, 28), Arguments.of(90, 14), Arguments.of(5591, 37), Arguments.of(5895, 130), Arguments.of(9950, 198), Arguments.of(9974, 4986)); } private static Stream<Arguments> provideNumbersForComputeDigitsInBase() { return Stream.of(Arguments.of(0, 2, new ArrayList<>()), Arguments.of(5, 2, Arrays.asList(1, 0, 1)), Arguments.of(13, 2, Arrays.asList(1, 0, 1, 1)), Arguments.of(10, 3, Arrays.asList(1, 0, 1)), Arguments.of(15, 2, Arrays.asList(1, 1, 1, 1)), Arguments.of(101, 10, Arrays.asList(1, 0, 1)), Arguments.of(255, 16, Arrays.asList(15, 15)), Arguments.of(100, 10, Arrays.asList(0, 0, 1))); } private static Stream<Arguments> provideInvalidNumbersForComputeDigits() { return Stream.of(Arguments.of(-1, 2), Arguments.of(-10, 10), Arguments.of(-100, 5)); } private static Stream<Arguments> provideInvalidBasesForComputeDigits() { return Stream.of(Arguments.of(10, 1), Arguments.of(5, 0), Arguments.of(100, -1)); } private static Stream<Arguments> provideNegativeNumbersForLowestBasePalindrome() { return Stream.of(Arguments.of(-1), Arguments.of(-10), Arguments.of(-100)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java
src/test/java/com/thealgorithms/others/cn/HammingDistanceTest.java
package com.thealgorithms.others.cn; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; public class HammingDistanceTest { @Test public void checkForDifferentBits() { int answer = HammingDistance.compute("000", "011"); Assertions.assertThat(answer).isEqualTo(2); } /* 1 0 1 0 1 1 1 1 1 0 ---------- 0 1 0 1 1 */ @Test public void checkForDifferentBitsLength() { int answer = HammingDistance.compute("10101", "11110"); Assertions.assertThat(answer).isEqualTo(3); } @Test public void checkForSameBits() { String someBits = "111"; int answer = HammingDistance.compute(someBits, someBits); Assertions.assertThat(answer).isEqualTo(0); } @Test public void checkForLongDataBits() { int answer = HammingDistance.compute("10010101101010000100110100", "00110100001011001100110101"); Assertions.assertThat(answer).isEqualTo(7); } @Test public void mismatchDataBits() { Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("100010", "00011"); }); Assertions.assertThat(ex.getMessage()).contains("must have the same length"); } @Test public void mismatchDataBits2() { Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("1", "11"); }); Assertions.assertThat(ex.getMessage()).contains("must have the same length"); } @Test public void checkForLongDataBitsSame() { String someBits = "10010101101010000100110100"; int answer = HammingDistance.compute(someBits, someBits); Assertions.assertThat(answer).isEqualTo(0); } @Test public void checkForEmptyInput() { String someBits = ""; int answer = HammingDistance.compute(someBits, someBits); Assertions.assertThat(answer).isEqualTo(0); } @Test public void checkForInputOfLength1() { String someBits = "0"; int answer = HammingDistance.compute(someBits, someBits); Assertions.assertThat(answer).isEqualTo(0); } @Test public void computeThrowsExceptionWhenInputsAreNotBitStrs() { Exception ex = org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class, () -> { HammingDistance.compute("1A", "11"); }); Assertions.assertThat(ex.getMessage()).contains("must be a binary string"); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java
src/test/java/com/thealgorithms/slidingwindow/LongestSubstringWithoutRepeatingCharactersTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Unit tests for the LongestSubstringWithoutRepeatingCharacters class. * * @author (https://github.com/Chiefpatwal) */ public class LongestSubstringWithoutRepeatingCharactersTest { @Test public void testLengthOfLongestSubstring() { // Test cases for the lengthOfLongestSubstring method assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcabcbb")); assertEquals(1, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("bbbbb")); assertEquals(3, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("pwwkew")); assertEquals(0, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("")); assertEquals(5, LongestSubstringWithoutRepeatingCharacters.lengthOfLongestSubstring("abcde")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java
src/test/java/com/thealgorithms/slidingwindow/MinSumKSizeSubarrayTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Unit tests for the MinSumKSizeSubarray class. * * @author Rashi Dashore (https://github.com/rashi07dashore) */ class MinSumKSizeSubarrayTest { /** * Test for the basic case of finding the minimum sum. */ @Test void testMinSumKSizeSubarray() { int[] arr = {2, 1, 5, 1, 3, 2}; int k = 3; int expectedMinSum = 6; // Corrected: Minimum sum of a subarray of size 3 assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } /** * Test for a different array and subarray size. */ @Test void testMinSumKSizeSubarrayWithDifferentValues() { int[] arr = {1, 2, 3, 4, 5}; int k = 2; int expectedMinSum = 3; // 1 + 2 assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } /** * Test for edge case with insufficient elements. */ @Test void testMinSumKSizeSubarrayWithInsufficientElements() { int[] arr = {1, 2}; int k = 3; // Not enough elements int expectedMinSum = -1; // Edge case assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } /** * Test for large array. */ @Test void testMinSumKSizeSubarrayWithLargeArray() { int[] arr = {5, 4, 3, 2, 1, 0, -1, -2, -3, -4}; int k = 5; int expectedMinSum = -10; // -1 + -2 + -3 + -4 + 0 assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } /** * Test for array with negative numbers. */ @Test void testMinSumKSizeSubarrayWithNegativeNumbers() { int[] arr = {-1, -2, -3, -4, -5}; int k = 2; int expectedMinSum = -9; // -4 + -5 assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } /** * Test for the case where k equals the array length. */ @Test void testMinSumKSizeSubarrayWithKEqualToArrayLength() { int[] arr = {1, 2, 3, 4, 5}; int k = 5; int expectedMinSum = 15; // 1 + 2 + 3 + 4 + 5 assertEquals(expectedMinSum, MinSumKSizeSubarray.minSumKSizeSubarray(arr, k)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java
src/test/java/com/thealgorithms/slidingwindow/MinimumWindowSubstringTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Finds the minimum window substring in {@code s} that contains all characters of {@code t}. * * @param s The input string to search within * @param t The string with required characters * @return The minimum window substring, or empty string if not found * @author (https://github.com/Chiefpatwal) */ public class MinimumWindowSubstringTest { /** * Tests for MinimumWindowSubstring.minWindow. */ @Test public void testMinimumWindowSubstring() { assertEquals("BANC", MinimumWindowSubstring.minWindow("ADOBECODEBANC", "ABC")); assertEquals("a", MinimumWindowSubstring.minWindow("a", "a")); assertEquals("", MinimumWindowSubstring.minWindow("a", "aa")); assertEquals("", MinimumWindowSubstring.minWindow("ADOBECODEBANC", "XYZ")); assertEquals("BC", MinimumWindowSubstring.minWindow("ABCDEF", "BC")); assertEquals("q", MinimumWindowSubstring.minWindow("abcdefghijklmnopqrstuvwxyz", "q")); assertEquals("", MinimumWindowSubstring.minWindow("zzzzzzzzz", "zzzzzzzzzz")); assertEquals("abbbbbcdd", MinimumWindowSubstring.minWindow("aaaaaaaaaaaabbbbbcdd", "abcdd")); assertEquals("ABCDEFG", MinimumWindowSubstring.minWindow("ABCDEFG", "ABCDEFG")); assertEquals("", MinimumWindowSubstring.minWindow("abc", "A")); assertEquals("A", MinimumWindowSubstring.minWindow("aAbBcC", "A")); assertEquals("AABBC", MinimumWindowSubstring.minWindow("AAABBC", "AABC")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java
src/test/java/com/thealgorithms/slidingwindow/MaxSumKSizeSubarrayTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Unit tests for the MaxSumKSizeSubarray class. * * @author Your Name (https://github.com/Chiefpatwal) */ class MaxSumKSizeSubarrayTest { /** * Test for the basic case of finding the maximum sum. */ @Test void testMaxSumKSizeSubarray() { int[] arr = {1, 2, 3, 4, 5}; int k = 2; int expectedMaxSum = 9; // 4 + 5 assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } /** * Test for a different array and subarray size. */ @Test void testMaxSumKSizeSubarrayWithDifferentValues() { int[] arr = {2, 1, 5, 1, 3, 2}; int k = 3; int expectedMaxSum = 9; // 5 + 1 + 3 assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } /** * Test for edge case with insufficient elements. */ @Test void testMaxSumKSizeSubarrayWithInsufficientElements() { int[] arr = {1, 2}; int k = 3; // Not enough elements int expectedMaxSum = -1; // Edge case assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } /** * Test for large array. */ @Test void testMaxSumKSizeSubarrayWithLargeArray() { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int k = 5; int expectedMaxSum = 40; // 6 + 7 + 8 + 9 + 10 assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } /** * Test for array with negative numbers. */ @Test void testMaxSumKSizeSubarrayWithNegativeNumbers() { int[] arr = {-1, -2, -3, -4, -5}; int k = 2; int expectedMaxSum = -3; // -1 + -2 assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } /** * Test for the case where k equals the array length. */ @Test void testMaxSumKSizeSubarrayWithKEqualToArrayLength() { int[] arr = {1, 2, 3, 4, 5}; int k = 5; int expectedMaxSum = 15; // 1 + 2 + 3 + 4 + 5 assertEquals(expectedMaxSum, MaxSumKSizeSubarray.maxSumKSizeSubarray(arr, k)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToKTest.java
src/test/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToKTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; /** * Unit tests for the LongestSubarrayWithSumLessOrEqualToK algorithm. */ public class LongestSubarrayWithSumLessOrEqualToKTest { /** * Tests for the longest subarray with a sum less than or equal to k. */ @Test public void testLongestSubarrayWithSumLEK() { assertEquals(3, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 6)); // {1, 2, 3} assertEquals(4, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 10)); // {1, 2, 3, 4} assertEquals(2, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {5, 1, 2, 3}, 5)); // {5} assertEquals(0, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3}, 0)); // No valid subarray } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/MaximumSlidingWindowTest.java
src/test/java/com/thealgorithms/slidingwindow/MaximumSlidingWindowTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class MaximumSlidingWindowTest { MaximumSlidingWindow msw; int[] nums; int k; @BeforeEach void setUp() { msw = new MaximumSlidingWindow(); // Initialize the MaximumSlidingWindow object } // Test for a simple sliding window case @Test void testMaxSlidingWindowSimpleCase() { nums = new int[] {1, 3, -1, -3, 5, 3, 6, 7}; k = 3; int[] expected = {3, 3, 5, 5, 6, 7}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); } // Test when window size is 1 (output should be the array itself) @Test void testMaxSlidingWindowWindowSizeOne() { nums = new int[] {4, 2, 12, 11, -5}; k = 1; int[] expected = {4, 2, 12, 11, -5}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); } // Test when the window size is equal to the array length (output should be a single max element) @Test void testMaxSlidingWindowWindowSizeEqualsArrayLength() { nums = new int[] {4, 2, 12, 11, -5}; k = nums.length; int[] expected = {12}; // Maximum of the entire array assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); } // Test when the input array is empty @Test void testMaxSlidingWindowEmptyArray() { nums = new int[] {}; k = 3; int[] expected = {}; assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); } // Test when the window size is larger than the array (should return empty) @Test void testMaxSlidingWindowWindowSizeLargerThanArray() { nums = new int[] {1, 2, 3}; k = 5; int[] expected = {}; // Window size is too large, so no result assertArrayEquals(expected, msw.maxSlidingWindow(nums, k)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegmentTest.java
src/test/java/com/thealgorithms/slidingwindow/ShortestCoprimeSegmentTest.java
package com.thealgorithms.slidingwindow; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import java.util.Arrays; import org.junit.jupiter.api.Test; /** * Unit tests for ShortestCoprimeSegment algorithm * * @author DomTr (<a href="https://github.com/DomTr">...</a>) */ public class ShortestCoprimeSegmentTest { @Test public void testShortestCoprimeSegment() { assertArrayEquals(new long[] {4, 6, 9}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {4, 6, 9, 3, 6})); assertArrayEquals(new long[] {4, 5}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {4, 5, 9, 3, 6})); assertArrayEquals(new long[] {3, 2}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {3, 2})); assertArrayEquals(new long[] {9, 10}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {3, 9, 9, 9, 10})); long[] test5 = new long[] {3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 11 * 7 * 3 * 5 * 13, 7 * 13, 11 * 7 * 3 * 5 * 13}; long[] answer5 = Arrays.copyOfRange(test5, 0, test5.length - 1); assertArrayEquals(answer5, ShortestCoprimeSegment.shortestCoprimeSegment(test5)); // Test suite, when the entire array needs to be taken long[] test6 = new long[] {3 * 7, 7 * 5, 5 * 7 * 3, 3 * 5}; assertArrayEquals(test6, ShortestCoprimeSegment.shortestCoprimeSegment(test6)); long[] test7 = new long[] {3 * 11, 11 * 7, 11 * 7 * 3, 3 * 7}; assertArrayEquals(test7, ShortestCoprimeSegment.shortestCoprimeSegment(test7)); long[] test8 = new long[] {3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 5 * 7}; assertArrayEquals(test8, ShortestCoprimeSegment.shortestCoprimeSegment(test8)); long[] test9 = new long[] {3 * 11, 11 * 7, 11 * 7 * 3, 11 * 7 * 3 * 5, 11 * 7 * 3 * 5 * 13, 7 * 13}; assertArrayEquals(test9, ShortestCoprimeSegment.shortestCoprimeSegment(test9)); long[] test10 = new long[] {3 * 11, 7 * 11, 3 * 7 * 11, 3 * 5 * 7 * 11, 3 * 5 * 7 * 11 * 13, 2 * 3 * 5 * 7 * 11 * 13, 2 * 3 * 5 * 7 * 11 * 13 * 17, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19, 2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23, 7 * 13}; assertArrayEquals(test10, ShortestCoprimeSegment.shortestCoprimeSegment(test10)); // Segment can consist of one element long[] test11 = new long[] {1}; assertArrayEquals(test11, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {4, 6, 1, 3, 6})); long[] test12 = new long[] {1}; assertArrayEquals(test12, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {1})); } @Test public void testShortestCoprimeSegment2() { assertArrayEquals(new long[] {2 * 3, 2 * 3 * 5, 2 * 3 * 5 * 7, 5 * 7}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {2 * 3, 2 * 3 * 5, 2 * 3 * 5 * 7, 5 * 7, 2 * 3 * 5 * 7})); assertArrayEquals(new long[] {5 * 7, 2}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {2 * 3, 2 * 3 * 5, 2 * 3 * 5 * 7, 5 * 7, 2})); assertArrayEquals(new long[] {5 * 7, 2 * 5 * 7, 2 * 11}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {2 * 3, 2 * 3 * 5, 2 * 3 * 5 * 7, 5 * 7, 2 * 5 * 7, 2 * 11})); assertArrayEquals(new long[] {3 * 5 * 7, 2 * 3, 2}, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {2, 2 * 3, 2 * 3 * 5, 3 * 5 * 7, 2 * 3, 2})); } @Test public void testNoCoprimeSegment() { // There may not be a coprime segment long[] empty = new long[] {}; assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(null)); assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(empty)); assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {4, 6, 8, 12, 8})); assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {4, 4, 4, 4, 10, 4, 6, 8, 12, 8})); assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {100})); assertArrayEquals(empty, ShortestCoprimeSegment.shortestCoprimeSegment(new long[] {2, 2, 2})); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/TilingProblemTest.java
src/test/java/com/thealgorithms/divideandconquer/TilingProblemTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; public class TilingProblemTest { @Test public void testTilingSize2() { int[][] expected = {{1, 1}, {1, 0}}; int[][] result = TilingProblem.solveTiling(2, 1, 1); assertArrayEquals(expected, result); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java
src/test/java/com/thealgorithms/divideandconquer/ClosestPairTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; public class ClosestPairTest { @Test public void testBuildLocation() { ClosestPair cp = new ClosestPair(1); ClosestPair.Location point = cp.buildLocation(3.0, 4.0); assertNotNull(point); assertEquals(3.0, point.x); assertEquals(4.0, point.y); } @Test public void testCreateLocation() { ClosestPair cp = new ClosestPair(5); ClosestPair.Location[] locations = cp.createLocation(5); assertNotNull(locations); assertEquals(5, locations.length); } @Test public void testXPartition() { ClosestPair cp = new ClosestPair(5); ClosestPair.Location[] points = new ClosestPair.Location[5]; points[0] = cp.buildLocation(2.0, 3.0); points[1] = cp.buildLocation(5.0, 1.0); points[2] = cp.buildLocation(1.0, 6.0); points[3] = cp.buildLocation(4.0, 7.0); points[4] = cp.buildLocation(3.0, 2.0); int pivotIndex = cp.xPartition(points, 0, 4); assertEquals(2, pivotIndex); assertEquals(2.0, points[0].x); assertEquals(1.0, points[1].x); assertEquals(3.0, points[2].x); assertEquals(4.0, points[3].x); assertEquals(5.0, points[4].x); } @Test public void testYPartition() { ClosestPair cp = new ClosestPair(5); ClosestPair.Location[] points = new ClosestPair.Location[5]; points[0] = cp.buildLocation(2.0, 3.0); points[1] = cp.buildLocation(5.0, 1.0); points[2] = cp.buildLocation(1.0, 6.0); points[3] = cp.buildLocation(4.0, 7.0); points[4] = cp.buildLocation(3.0, 2.0); int pivotIndex = cp.yPartition(points, 0, 4); assertEquals(1, pivotIndex); assertEquals(2.0, points[1].y); assertEquals(3.0, points[4].y); assertEquals(1.0, points[0].y); assertEquals(6.0, points[2].y); assertEquals(7.0, points[3].y); } @Test public void testBruteForce() { ClosestPair cp = new ClosestPair(2); ClosestPair.Location loc1 = cp.buildLocation(1.0, 2.0); ClosestPair.Location loc2 = cp.buildLocation(4.0, 6.0); ClosestPair.Location[] locations = new ClosestPair.Location[] {loc1, loc2}; double result = cp.bruteForce(locations); assertEquals(5.0, result, 0.01); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java
src/test/java/com/thealgorithms/divideandconquer/MedianOfTwoSortedArraysTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; public class MedianOfTwoSortedArraysTest { @ParameterizedTest @MethodSource("provideTestCases") void testFindMedianSortedArrays(int[] nums1, int[] nums2, double expectedMedian) { assertEquals(expectedMedian, MedianOfTwoSortedArrays.findMedianSortedArrays(nums1, nums2)); } private static Stream<Arguments> provideTestCases() { return Stream.of( // Test case 1: Arrays of equal length Arguments.of(new int[] {1, 3}, new int[] {2, 4}, 2.5), // Test case 2: Arrays of different lengths Arguments.of(new int[] {1, 3}, new int[] {2}, 2.0), // Test case 3: Arrays with even total length Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5, 6, 7}, 4.5), // Test case 4: Arrays with odd total length Arguments.of(new int[] {1, 2, 8}, new int[] {3, 4, 5}, 3.5), // Test case 5: Single element arrays Arguments.of(new int[] {1}, new int[] {3}, 2.0), // Test case 6: Empty arrays Arguments.of(new int[] {}, new int[] {0}, 0.0), // Test case 7: Same element arrays Arguments.of(new int[] {2, 2, 2}, new int[] {2, 2, 2}, 2.0)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
src/test/java/com/thealgorithms/divideandconquer/StrassenMatrixMultiplicationTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import org.junit.jupiter.api.Test; class StrassenMatrixMultiplicationTest { StrassenMatrixMultiplication smm = new StrassenMatrixMultiplication(); // Strassen Matrix Multiplication can only be allplied to matrices of size 2^n // and has to be a Square Matrix @Test public void strassenMatrixMultiplicationTest2x2() { int[][] a = {{1, 2}, {3, 4}}; int[][] b = {{5, 6}, {7, 8}}; int[][] expResult = {{19, 22}, {43, 50}}; int[][] actResult = smm.multiply(a, b); assertArrayEquals(expResult, actResult); } @Test void strassenMatrixMultiplicationTest4x4() { int[][] a = {{1, 2, 5, 4}, {9, 3, 0, 6}, {4, 6, 3, 1}, {0, 2, 0, 6}}; int[][] b = {{1, 0, 4, 1}, {1, 2, 0, 2}, {0, 3, 1, 3}, {1, 8, 1, 2}}; int[][] expResult = {{7, 51, 13, 28}, {18, 54, 42, 27}, {11, 29, 20, 27}, {8, 52, 6, 16}}; int[][] actResult = smm.multiply(a, b); assertArrayEquals(expResult, actResult); } @Test void strassenMatrixMultiplicationTestNegetiveNumber4x4() { int[][] a = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}; int[][] b = {{1, -2, -3, 4}, {4, -3, -2, 1}, {5, -6, -7, 8}, {8, -7, -6, -5}}; int[][] expResult = {{56, -54, -52, 10}, {128, -126, -124, 42}, {200, -198, -196, 74}, {272, -270, -268, 106}}; int[][] actResult = smm.multiply(a, b); assertArrayEquals(expResult, actResult); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java
src/test/java/com/thealgorithms/divideandconquer/BinaryExponentiationTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class BinaryExponentiationTest { @Test public void testCalculatePower() { assertEquals(1, BinaryExponentiation.calculatePower(1, 10000000)); assertEquals(1, BinaryExponentiation.calculatePower(1, 100000000)); assertEquals(1, BinaryExponentiation.calculatePower(1, 1000000000)); assertEquals(1, BinaryExponentiation.calculatePower(1, 10000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 100000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 1000000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 10000000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 100000000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 1000000000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 10000000000000000L)); assertEquals(1, BinaryExponentiation.calculatePower(1, 100000000000000000L)); } @Test public void testPower() { assertEquals(1, new BinaryExponentiation().power(1, 10000000)); assertEquals(1, new BinaryExponentiation().power(1, 100000000)); assertEquals(1, new BinaryExponentiation().power(1, 1000000000)); assertEquals(1, new BinaryExponentiation().power(1, 10000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 100000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 1000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 10000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 100000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 1000000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 10000000000000000L)); assertEquals(1, new BinaryExponentiation().power(1, 100000000000000000L)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/CountingInversionsTest.java
src/test/java/com/thealgorithms/divideandconquer/CountingInversionsTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; public class CountingInversionsTest { @Test public void testCountInversions() { int[] arr = {2, 3, 8, 6, 1}; assertEquals(5, CountingInversions.countInversions(arr)); } @Test public void testNoInversions() { int[] arr = {1, 2, 3, 4, 5}; assertEquals(0, CountingInversions.countInversions(arr)); } @Test public void testSingleElement() { int[] arr = {1}; assertEquals(0, CountingInversions.countInversions(arr)); } @Test public void testAllInversions() { int[] arr = {5, 4, 3, 2, 1}; assertEquals(10, CountingInversions.countInversions(arr)); } @Test public void testEmptyArray() { int[] arr = {}; assertEquals(0, CountingInversions.countInversions(arr)); } @Test public void testArrayWithDuplicates() { int[] arr = {1, 3, 2, 3, 1}; // Inversions: (3,2), (3,1), (3,1), (2,1) assertEquals(4, CountingInversions.countInversions(arr)); } @Test public void testLargeArray() { int n = 1000; int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = n - i; // descending order -> max inversions = n*(n-1)/2 } int expected = n * (n - 1) / 2; assertEquals(expected, CountingInversions.countInversions(arr)); } @Test public void testArrayWithAllSameElements() { int[] arr = {7, 7, 7, 7}; // No inversions since all elements are equal assertEquals(0, CountingInversions.countInversions(arr)); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java
src/test/java/com/thealgorithms/divideandconquer/SkylineAlgorithmTest.java
package com.thealgorithms.divideandconquer; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.ArrayList; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class SkylineAlgorithmTest { private SkylineAlgorithm skylineAlgorithm; @BeforeEach public void setUp() { skylineAlgorithm = new SkylineAlgorithm(); } @Test public void testProduceSubSkyLinesSinglePoint() { // Test with a single point ArrayList<SkylineAlgorithm.Point> points = new ArrayList<>(); points.add(new SkylineAlgorithm.Point(1, 10)); ArrayList<SkylineAlgorithm.Point> result = skylineAlgorithm.produceSubSkyLines(points); assertEquals(1, result.size()); assertEquals(1, result.get(0).getX()); assertEquals(10, result.get(0).getY()); } @Test public void testProduceSubSkyLinesTwoPoints() { // Test with two points, one dominated by the other ArrayList<SkylineAlgorithm.Point> points = new ArrayList<>(); points.add(new SkylineAlgorithm.Point(1, 10)); points.add(new SkylineAlgorithm.Point(1, 5)); ArrayList<SkylineAlgorithm.Point> result = skylineAlgorithm.produceSubSkyLines(points); assertEquals(1, result.size()); assertEquals(1, result.get(0).getX()); assertEquals(5, result.get(0).getY()); } @Test public void testProduceSubSkyLinesMultiplePoints() { // Test with more than two points ArrayList<SkylineAlgorithm.Point> points = new ArrayList<>(); points.add(new SkylineAlgorithm.Point(1, 10)); points.add(new SkylineAlgorithm.Point(2, 15)); points.add(new SkylineAlgorithm.Point(3, 5)); points.add(new SkylineAlgorithm.Point(4, 20)); ArrayList<SkylineAlgorithm.Point> result = skylineAlgorithm.produceSubSkyLines(points); assertEquals(2, result.size()); // Assert the correct points in skyline assertEquals(1, result.get(0).getX()); assertEquals(10, result.get(0).getY()); assertEquals(3, result.get(1).getX()); assertEquals(5, result.get(1).getY()); } @Test public void testProduceFinalSkyLine() { // Test merging two skylines ArrayList<SkylineAlgorithm.Point> left = new ArrayList<>(); left.add(new SkylineAlgorithm.Point(1, 10)); left.add(new SkylineAlgorithm.Point(2, 5)); ArrayList<SkylineAlgorithm.Point> right = new ArrayList<>(); right.add(new SkylineAlgorithm.Point(3, 8)); right.add(new SkylineAlgorithm.Point(4, 3)); ArrayList<SkylineAlgorithm.Point> result = skylineAlgorithm.produceFinalSkyLine(left, right); assertEquals(3, result.size()); // Assert the correct points in the final skyline assertEquals(1, result.get(0).getX()); assertEquals(10, result.get(0).getY()); assertEquals(2, result.get(1).getX()); assertEquals(5, result.get(1).getY()); assertEquals(4, result.get(2).getX()); assertEquals(3, result.get(2).getY()); } @Test public void testXComparator() { // Test the XComparator used for sorting the points SkylineAlgorithm.XComparator comparator = new SkylineAlgorithm().new XComparator(); SkylineAlgorithm.Point p1 = new SkylineAlgorithm.Point(1, 10); SkylineAlgorithm.Point p2 = new SkylineAlgorithm.Point(2, 5); // Check if the XComparator sorts points by their x-value assertEquals(-1, comparator.compare(p1, p2)); // p1.x < p2.x assertEquals(1, comparator.compare(p2, p1)); // p2.x > p1.x assertEquals(0, comparator.compare(p1, new SkylineAlgorithm.Point(1, 15))); // p1.x == p2.x } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/PowerSum.java
src/main/java/com/thealgorithms/backtracking/PowerSum.java
package com.thealgorithms.backtracking; /** * Problem Statement: * Find the number of ways that a given integer, N, can be expressed as the sum of the Xth powers * of unique, natural numbers. * For example, if N=100 and X=3, we have to find all combinations of unique cubes adding up to 100. * The only solution is 1^3 + 2^3 + 3^3 + 4^3. Therefore, the output will be 1. * * N is represented by the parameter 'targetSum' in the code. * X is represented by the parameter 'power' in the code. */ public class PowerSum { /** * Calculates the number of ways to express the target sum as a sum of Xth powers of unique natural numbers. * * @param targetSum The target sum to achieve (N in the problem statement) * @param power The power to raise natural numbers to (X in the problem statement) * @return The number of ways to express the target sum */ public int powSum(int targetSum, int power) { // Special case: when both targetSum and power are zero if (targetSum == 0 && power == 0) { return 1; // by convention, one way to sum to zero: use nothing } return sumRecursive(targetSum, power, 1, 0); } /** * Recursively calculates the number of ways to express the remaining sum as a sum of Xth powers. * * @param remainingSum The remaining sum to achieve * @param power The power to raise natural numbers to (X in the problem statement) * @param currentNumber The current natural number being considered * @param currentSum The current sum of powered numbers * @return The number of valid combinations */ private int sumRecursive(int remainingSum, int power, int currentNumber, int currentSum) { int newSum = currentSum + (int) Math.pow(currentNumber, power); if (newSum == remainingSum) { return 1; } if (newSum > remainingSum) { return 0; } return sumRecursive(remainingSum, power, currentNumber + 1, newSum) + sumRecursive(remainingSum, power, currentNumber + 1, currentSum); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/KnightsTour.java
src/main/java/com/thealgorithms/backtracking/KnightsTour.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * The KnightsTour class solves the Knight's Tour problem using backtracking. * * Problem Statement: * Given an N*N board with a knight placed on the first block, the knight must * move according to chess rules and visit each square on the board exactly once. * The class outputs the sequence of moves for the knight. * * Example: * Input: N = 8 (8x8 chess board) * Output: The sequence of numbers representing the order in which the knight visits each square. */ public final class KnightsTour { private KnightsTour() { } // The size of the chess board (12x12 grid, with 2 extra rows/columns as a buffer around a 8x8 area) private static final int BASE = 12; // Possible moves for a knight in chess private static final int[][] MOVES = { {1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}, }; // Chess grid representing the board static int[][] grid; // Total number of cells the knight needs to visit static int total; /** * Resets the chess board to its initial state. * Initializes the grid with boundary cells marked as -1 and internal cells as 0. * Sets the total number of cells the knight needs to visit. */ public static void resetBoard() { grid = new int[BASE][BASE]; total = (BASE - 4) * (BASE - 4); for (int r = 0; r < BASE; r++) { for (int c = 0; c < BASE; c++) { if (r < 2 || r > BASE - 3 || c < 2 || c > BASE - 3) { grid[r][c] = -1; // Mark boundary cells } } } } /** * Recursive method to solve the Knight's Tour problem. * * @param row The current row of the knight * @param column The current column of the knight * @param count The current move number * @return True if a solution is found, False otherwise */ static boolean solve(int row, int column, int count) { if (count > total) { return true; } List<int[]> neighbor = neighbors(row, column); if (neighbor.isEmpty() && count != total) { return false; } // Sort neighbors by Warnsdorff's rule (fewest onward moves) neighbor.sort(Comparator.comparingInt(a -> a[2])); for (int[] nb : neighbor) { int nextRow = nb[0]; int nextCol = nb[1]; grid[nextRow][nextCol] = count; if (!orphanDetected(count, nextRow, nextCol) && solve(nextRow, nextCol, count + 1)) { return true; } grid[nextRow][nextCol] = 0; // Backtrack } return false; } /** * Returns a list of valid neighboring cells where the knight can move. * * @param row The current row of the knight * @param column The current column of the knight * @return A list of arrays representing valid moves, where each array contains: * {nextRow, nextCol, numberOfPossibleNextMoves} */ static List<int[]> neighbors(int row, int column) { List<int[]> neighbour = new ArrayList<>(); for (int[] m : MOVES) { int x = m[0]; int y = m[1]; if (row + y >= 0 && row + y < BASE && column + x >= 0 && column + x < BASE && grid[row + y][column + x] == 0) { int num = countNeighbors(row + y, column + x); neighbour.add(new int[] {row + y, column + x, num}); } } return neighbour; } /** * Counts the number of possible valid moves for a knight from a given position. * * @param row The row of the current position * @param column The column of the current position * @return The number of valid neighboring moves */ static int countNeighbors(int row, int column) { int num = 0; for (int[] m : MOVES) { int x = m[0]; int y = m[1]; if (row + y >= 0 && row + y < BASE && column + x >= 0 && column + x < BASE && grid[row + y][column + x] == 0) { num++; } } return num; } /** * Detects if moving to a given position will create an orphan (a position with no further valid moves). * * @param count The current move number * @param row The row of the current position * @param column The column of the current position * @return True if an orphan is detected, False otherwise */ static boolean orphanDetected(int count, int row, int column) { if (count < total - 1) { List<int[]> neighbor = neighbors(row, column); for (int[] nb : neighbor) { if (countNeighbors(nb[0], nb[1]) == 0) { 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/backtracking/ArrayCombination.java
src/main/java/com/thealgorithms/backtracking/ArrayCombination.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.List; /** * This class provides methods to find all combinations of integers from 0 to n-1 * of a specified length k using backtracking. */ public final class ArrayCombination { private ArrayCombination() { } /** * Generates all possible combinations of length k from the integers 0 to n-1. * * @param n The total number of elements (0 to n-1). * @param k The desired length of each combination. * @return A list containing all combinations of length k. * @throws IllegalArgumentException if n or k are negative, or if k is greater than n. */ public static List<List<Integer>> combination(int n, int k) { if (n < 0 || k < 0 || k > n) { throw new IllegalArgumentException("Invalid input: n must be non-negative, k must be non-negative and less than or equal to n."); } List<List<Integer>> combinations = new ArrayList<>(); combine(combinations, new ArrayList<>(), 0, n, k); return combinations; } /** * A helper method that uses backtracking to find combinations. * * @param combinations The list to store all valid combinations found. * @param current The current combination being built. * @param start The starting index for the current recursion. * @param n The total number of elements (0 to n-1). * @param k The desired length of each combination. */ private static void combine(List<List<Integer>> combinations, List<Integer> current, int start, int n, int k) { // Base case: combination found if (current.size() == k) { combinations.add(new ArrayList<>(current)); return; } for (int i = start; i < n; i++) { current.add(i); combine(combinations, current, i + 1, n, k); current.remove(current.size() - 1); // Backtrack } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/MColoring.java
src/main/java/com/thealgorithms/backtracking/MColoring.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.Set; /** * Node class represents a graph node. Each node is associated with a color * (initially 1) and contains a set of edges representing its adjacent nodes. * * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ class Node { int color = 1; // Initial color for each node Set<Integer> edges = new HashSet<Integer>(); // Set of edges representing adjacent nodes } /** * MColoring class solves the M-Coloring problem where the goal is to determine * if it's possible to color a graph using at most M colors such that no two * adjacent nodes have the same color. */ public final class MColoring { private MColoring() { } // Prevent instantiation of utility class /** * Determines whether it is possible to color the graph using at most M colors. * * @param nodes List of nodes representing the graph. * @param n The total number of nodes in the graph. * @param m The maximum number of allowed colors. * @return true if the graph can be colored using M colors, false otherwise. */ static boolean isColoringPossible(ArrayList<Node> nodes, int n, int m) { // Visited array keeps track of whether each node has been processed. ArrayList<Integer> visited = new ArrayList<Integer>(); for (int i = 0; i < n + 1; i++) { visited.add(0); // Initialize all nodes as unvisited (0) } // The number of colors used so far (initially set to 1, since all nodes // start with color 1). int maxColors = 1; // Loop through all the nodes to ensure every node is visited, in case the // graph is disconnected. for (int sv = 1; sv <= n; sv++) { if (visited.get(sv) > 0) { continue; // Skip nodes that are already visited } // If the node is unvisited, mark it as visited and add it to the queue for BFS. visited.set(sv, 1); Queue<Integer> q = new LinkedList<>(); q.add(sv); // Perform BFS to process all nodes and their adjacent nodes while (q.size() != 0) { int top = q.peek(); // Get the current node from the queue q.remove(); // Check all adjacent nodes of the current node for (int it : nodes.get(top).edges) { // If the adjacent node has the same color as the current node, increment its // color to avoid conflict. if (nodes.get(top).color == nodes.get(it).color) { nodes.get(it).color += 1; } // Keep track of the maximum number of colors used so far maxColors = Math.max(maxColors, Math.max(nodes.get(top).color, nodes.get(it).color)); // If the number of colors used exceeds the allowed limit M, return false. if (maxColors > m) { return false; } // If the adjacent node hasn't been visited yet, mark it as visited and add it // to the queue for further processing. if (visited.get(it) == 0) { visited.set(it, 1); q.add(it); } } } } return true; // Possible to color the entire graph with M or fewer colors. } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/FloodFill.java
src/main/java/com/thealgorithms/backtracking/FloodFill.java
package com.thealgorithms.backtracking; /** * Java program for Flood fill algorithm. * @author Akshay Dubey (<a href="https://github.com/itsAkshayDubey">Git-Akshay Dubey</a>) */ public final class FloodFill { private FloodFill() { } /** * Get the color at the given coordinates of a 2D image * * @param image The image to be filled * @param x The x coordinate of which color is to be obtained * @param y The y coordinate of which color is to be obtained */ public static int getPixel(final int[][] image, final int x, final int y) { return image[x][y]; } /** * Put the color at the given coordinates of a 2D image * * @param image The image to be filled * @param x The x coordinate at which color is to be filled * @param y The y coordinate at which color is to be filled */ public static void putPixel(final int[][] image, final int x, final int y, final int newColor) { image[x][y] = newColor; } /** * Fill the 2D image with new color * * @param image The image to be filled * @param x The x coordinate at which color is to be filled * @param y The y coordinate at which color is to be filled * @param newColor The new color which to be filled in the image * @param oldColor The old color which is to be replaced in the image */ public static void floodFill(final int[][] image, final int x, final int y, final int newColor, final int oldColor) { if (newColor == oldColor || x < 0 || x >= image.length || y < 0 || y >= image[x].length || getPixel(image, x, y) != oldColor) { return; } putPixel(image, x, y, newColor); /* Recursively check for horizontally & vertically adjacent coordinates */ floodFill(image, x + 1, y, newColor, oldColor); floodFill(image, x - 1, y, newColor, oldColor); floodFill(image, x, y + 1, newColor, oldColor); floodFill(image, x, y - 1, newColor, oldColor); /* Recursively check for diagonally adjacent coordinates */ floodFill(image, x + 1, y - 1, newColor, oldColor); floodFill(image, x - 1, y + 1, newColor, oldColor); floodFill(image, x + 1, y + 1, newColor, oldColor); floodFill(image, x - 1, y - 1, newColor, oldColor); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java
src/main/java/com/thealgorithms/backtracking/ParenthesesGenerator.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.List; /** * This class generates all valid combinations of parentheses for a given number of pairs using backtracking. */ public final class ParenthesesGenerator { private ParenthesesGenerator() { } /** * Generates all valid combinations of parentheses for a given number of pairs. * * @param n The number of pairs of parentheses. * @return A list of strings representing valid combinations of parentheses. * @throws IllegalArgumentException if n is less than 0. */ public static List<String> generateParentheses(final int n) { if (n < 0) { throw new IllegalArgumentException("The number of pairs of parentheses cannot be negative"); } List<String> result = new ArrayList<>(); generateParenthesesHelper(result, "", 0, 0, n); return result; } /** * Helper function for generating all valid combinations of parentheses recursively. * * @param result The list to store valid combinations. * @param current The current combination being formed. * @param open The number of open parentheses. * @param close The number of closed parentheses. * @param n The total number of pairs of parentheses. */ private static void generateParenthesesHelper(List<String> result, final String current, final int open, final int close, final int n) { if (current.length() == n * 2) { result.add(current); return; } if (open < n) { generateParenthesesHelper(result, current + "(", open + 1, close, n); } if (close < open) { generateParenthesesHelper(result, current + ")", open, close + 1, n); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/Combination.java
src/main/java/com/thealgorithms/backtracking/Combination.java
package com.thealgorithms.backtracking; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.TreeSet; /** * Finds all combinations of a given array using backtracking algorithm * @author Alan Piao (<a href="https://github.com/cpiao3">git-Alan Piao</a>) */ public final class Combination { private Combination() { } /** * Find all combinations of given array using backtracking * @param arr the array. * @param n length of combination * @param <T> the type of elements in the array. * @return a list of all combinations of length n. If n == 0, return null. */ public static <T> List<TreeSet<T>> combination(T[] arr, int n) { if (n < 0) { throw new IllegalArgumentException("The combination length cannot be negative."); } if (n == 0) { return Collections.emptyList(); } T[] array = arr.clone(); Arrays.sort(array); List<TreeSet<T>> result = new LinkedList<>(); backtracking(array, n, 0, new TreeSet<T>(), result); return result; } /** * Backtrack all possible combinations of a given array * @param arr the array. * @param n length of the combination * @param index the starting index. * @param currSet set that tracks current combination * @param result the list contains all combination. * @param <T> the type of elements in the array. */ private static <T> void backtracking(T[] arr, int n, int index, TreeSet<T> currSet, List<TreeSet<T>> result) { if (index + n - currSet.size() > arr.length) { return; } if (currSet.size() == n - 1) { for (int i = index; i < arr.length; i++) { currSet.add(arr[i]); result.add(new TreeSet<>(currSet)); currSet.remove(arr[i]); } return; } for (int i = index; i < arr.length; i++) { currSet.add(arr[i]); backtracking(arr, n, i + 1, currSet, result); currSet.remove(arr[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/backtracking/SudokuSolver.java
src/main/java/com/thealgorithms/backtracking/SudokuSolver.java
package com.thealgorithms.backtracking; /** * Sudoku Solver using Backtracking Algorithm * Solves a 9x9 Sudoku puzzle by filling empty cells with valid digits (1-9) * * @author Navadeep0007 */ public final class SudokuSolver { private static final int GRID_SIZE = 9; private static final int SUBGRID_SIZE = 3; private static final int EMPTY_CELL = 0; private SudokuSolver() { // Utility class, prevent instantiation } /** * Solves the Sudoku puzzle using backtracking * * @param board 9x9 Sudoku board with 0 representing empty cells * @return true if puzzle is solved, false otherwise */ public static boolean solveSudoku(int[][] board) { if (board == null || board.length != GRID_SIZE) { return false; } for (int row = 0; row < GRID_SIZE; row++) { if (board[row].length != GRID_SIZE) { return false; } } return solve(board); } /** * Recursive helper method to solve the Sudoku puzzle * * @param board the Sudoku board * @return true if solution is found, false otherwise */ private static boolean solve(int[][] board) { for (int row = 0; row < GRID_SIZE; row++) { for (int col = 0; col < GRID_SIZE; col++) { if (board[row][col] == EMPTY_CELL) { for (int number = 1; number <= GRID_SIZE; number++) { if (isValidPlacement(board, row, col, number)) { board[row][col] = number; if (solve(board)) { return true; } // Backtrack board[row][col] = EMPTY_CELL; } } return false; } } } return true; } /** * Checks if placing a number at given position is valid * * @param board the Sudoku board * @param row row index * @param col column index * @param number number to place (1-9) * @return true if placement is valid, false otherwise */ private static boolean isValidPlacement(int[][] board, int row, int col, int number) { return !isNumberInRow(board, row, number) && !isNumberInColumn(board, col, number) && !isNumberInSubgrid(board, row, col, number); } /** * Checks if number exists in the given row * * @param board the Sudoku board * @param row row index * @param number number to check * @return true if number exists in row, false otherwise */ private static boolean isNumberInRow(int[][] board, int row, int number) { for (int col = 0; col < GRID_SIZE; col++) { if (board[row][col] == number) { return true; } } return false; } /** * Checks if number exists in the given column * * @param board the Sudoku board * @param col column index * @param number number to check * @return true if number exists in column, false otherwise */ private static boolean isNumberInColumn(int[][] board, int col, int number) { for (int row = 0; row < GRID_SIZE; row++) { if (board[row][col] == number) { return true; } } return false; } /** * Checks if number exists in the 3x3 subgrid * * @param board the Sudoku board * @param row row index * @param col column index * @param number number to check * @return true if number exists in subgrid, false otherwise */ private static boolean isNumberInSubgrid(int[][] board, int row, int col, int number) { int subgridRowStart = row - row % SUBGRID_SIZE; int subgridColStart = col - col % SUBGRID_SIZE; for (int i = subgridRowStart; i < subgridRowStart + SUBGRID_SIZE; i++) { for (int j = subgridColStart; j < subgridColStart + SUBGRID_SIZE; j++) { if (board[i][j] == number) { return true; } } } return false; } /** * Prints the Sudoku board * * @param board the Sudoku board */ public static void printBoard(int[][] board) { for (int row = 0; row < GRID_SIZE; row++) { if (row % SUBGRID_SIZE == 0 && row != 0) { System.out.println("-----------"); } for (int col = 0; col < GRID_SIZE; col++) { if (col % SUBGRID_SIZE == 0 && col != 0) { System.out.print("|"); } System.out.print(board[row][col]); } System.out.println(); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java
src/main/java/com/thealgorithms/backtracking/SubsequenceFinder.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.List; /** * Class generates all subsequences for a given list of elements using backtracking */ public final class SubsequenceFinder { private SubsequenceFinder() { } /** * Find all subsequences of given list using backtracking * * @param sequence a list of items on the basis of which we need to generate all subsequences * @param <T> the type of elements in the array * @return a list of all subsequences */ public static <T> List<List<T>> generateAll(List<T> sequence) { List<List<T>> allSubSequences = new ArrayList<>(); if (sequence.isEmpty()) { allSubSequences.add(new ArrayList<>()); return allSubSequences; } List<T> currentSubsequence = new ArrayList<>(); backtrack(sequence, currentSubsequence, 0, allSubSequences); return allSubSequences; } /** * Iterate through each branch of states * We know that each state has exactly two branching * It terminates when it reaches the end of the given sequence * * @param sequence all elements * @param currentSubsequence current subsequence * @param index current index * @param allSubSequences contains all sequences * @param <T> the type of elements which we generate */ private static <T> void backtrack(List<T> sequence, List<T> currentSubsequence, final int index, List<List<T>> allSubSequences) { assert index <= sequence.size(); if (index == sequence.size()) { allSubSequences.add(new ArrayList<>(currentSubsequence)); return; } backtrack(sequence, currentSubsequence, index + 1, allSubSequences); currentSubsequence.add(sequence.get(index)); backtrack(sequence, currentSubsequence, index + 1, allSubSequences); currentSubsequence.removeLast(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/Permutation.java
src/main/java/com/thealgorithms/backtracking/Permutation.java
package com.thealgorithms.backtracking; import java.util.LinkedList; import java.util.List; /** * Finds all permutations of given array * @author Alan Piao (<a href="https://github.com/cpiao3">Git-Alan Piao</a>) */ public final class Permutation { private Permutation() { } /** * Find all permutations of given array using backtracking * @param arr the array. * @param <T> the type of elements in the array. * @return a list of all permutations. */ public static <T> List<T[]> permutation(T[] arr) { T[] array = arr.clone(); List<T[]> result = new LinkedList<>(); backtracking(array, 0, result); return result; } /** * Backtrack all possible orders of a given array * @param arr the array. * @param index the starting index. * @param result the list contains all permutations. * @param <T> the type of elements in the array. */ private static <T> void backtracking(T[] arr, int index, List<T[]> result) { if (index == arr.length) { result.add(arr.clone()); } for (int i = index; i < arr.length; i++) { swap(index, i, arr); backtracking(arr, index + 1, result); swap(index, i, arr); } } /** * Swap two element for a given array * @param a first index * @param b second index * @param arr the array. * @param <T> the type of elements in the array. */ private static <T> void swap(int a, int b, T[] arr) { T temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java
src/main/java/com/thealgorithms/backtracking/CrosswordSolver.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * A class to solve a crossword puzzle using backtracking. * Example: * Input: * puzzle = { * {' ', ' ', ' '}, * {' ', ' ', ' '}, * {' ', ' ', ' '} * } * words = List.of("cat", "dog") * * Output: * { * {'c', 'a', 't'}, * {' ', ' ', ' '}, * {'d', 'o', 'g'} * } */ public final class CrosswordSolver { private CrosswordSolver() { } /** * Checks if a word can be placed at the specified position in the crossword. * * @param puzzle The crossword puzzle represented as a 2D char array. * @param word The word to be placed. * @param row The row index where the word might be placed. * @param col The column index where the word might be placed. * @param vertical If true, the word is placed vertically; otherwise, horizontally. * @return true if the word can be placed, false otherwise. */ public static boolean isValid(char[][] puzzle, String word, int row, int col, boolean vertical) { for (int i = 0; i < word.length(); i++) { if (vertical) { if (row + i >= puzzle.length || puzzle[row + i][col] != ' ') { return false; } } else { if (col + i >= puzzle[0].length || puzzle[row][col + i] != ' ') { return false; } } } return true; } /** * Places a word at the specified position in the crossword. * * @param puzzle The crossword puzzle represented as a 2D char array. * @param word The word to be placed. * @param row The row index where the word will be placed. * @param col The column index where the word will be placed. * @param vertical If true, the word is placed vertically; otherwise, horizontally. */ public static void placeWord(char[][] puzzle, String word, int row, int col, boolean vertical) { for (int i = 0; i < word.length(); i++) { if (vertical) { puzzle[row + i][col] = word.charAt(i); } else { puzzle[row][col + i] = word.charAt(i); } } } /** * Removes a word from the specified position in the crossword. * * @param puzzle The crossword puzzle represented as a 2D char array. * @param word The word to be removed. * @param row The row index where the word is placed. * @param col The column index where the word is placed. * @param vertical If true, the word was placed vertically; otherwise, horizontally. */ public static void removeWord(char[][] puzzle, String word, int row, int col, boolean vertical) { for (int i = 0; i < word.length(); i++) { if (vertical) { puzzle[row + i][col] = ' '; } else { puzzle[row][col + i] = ' '; } } } /** * Solves the crossword puzzle using backtracking. * * @param puzzle The crossword puzzle represented as a 2D char array. * @param words The list of words to be placed. * @return true if the crossword is solved, false otherwise. */ public static boolean solveCrossword(char[][] puzzle, Collection<String> words) { // Create a mutable copy of the words list List<String> remainingWords = new ArrayList<>(words); for (int row = 0; row < puzzle.length; row++) { for (int col = 0; col < puzzle[0].length; col++) { if (puzzle[row][col] == ' ') { for (String word : new ArrayList<>(remainingWords)) { for (boolean vertical : new boolean[] {true, false}) { if (isValid(puzzle, word, row, col, vertical)) { placeWord(puzzle, word, row, col, vertical); remainingWords.remove(word); if (solveCrossword(puzzle, remainingWords)) { return true; } remainingWords.add(word); removeWord(puzzle, word, row, col, vertical); } } } 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/backtracking/AllPathsFromSourceToTarget.java
src/main/java/com/thealgorithms/backtracking/AllPathsFromSourceToTarget.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.List; /** * Program description - To find all possible paths from source to destination * <a href="https://en.wikipedia.org/wiki/Shortest_path_problem">Wikipedia</a> * * @author <a href="https://github.com/siddhant2002">Siddhant Swarup Mallick</a> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class AllPathsFromSourceToTarget { // No. of vertices in graph private final int v; // To store the paths from source to destination static List<List<Integer>> nm = new ArrayList<>(); // adjacency list private ArrayList<Integer>[] adjList; // Constructor public AllPathsFromSourceToTarget(int vertices) { // initialise vertex count this.v = vertices; // initialise adjacency list initAdjList(); } // utility method to initialise adjacency list private void initAdjList() { adjList = new ArrayList[v]; for (int i = 0; i < v; i++) { adjList[i] = new ArrayList<>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } public void storeAllPaths(int s, int d) { boolean[] isVisited = new boolean[v]; ArrayList<Integer> pathList = new ArrayList<>(); // add source to path[] pathList.add(s); // Call recursive utility storeAllPathsUtil(s, d, isVisited, pathList); } // A recursive function to print all paths from 'u' to 'd'. // isVisited[] keeps track of vertices in current path. // localPathList<> stores actual vertices in the current path private void storeAllPathsUtil(Integer u, Integer d, boolean[] isVisited, List<Integer> localPathList) { if (u.equals(d)) { nm.add(new ArrayList<>(localPathList)); return; } // Mark the current node isVisited[u] = true; // Recursion for all the vertices adjacent to current vertex for (Integer i : adjList[u]) { if (!isVisited[i]) { // store current node in path[] localPathList.add(i); storeAllPathsUtil(i, d, isVisited, localPathList); // remove current node in path[] localPathList.remove(i); } } // Mark the current node isVisited[u] = false; } // Driver program public static List<List<Integer>> allPathsFromSourceToTarget(int vertices, int[][] a, int source, int destination) { // Create a sample graph AllPathsFromSourceToTarget g = new AllPathsFromSourceToTarget(vertices); for (int[] i : a) { g.addEdge(i[0], i[1]); // edges are added } g.storeAllPaths(source, destination); // method call to store all possible paths return nm; // returns all possible paths from source to destination } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java
src/main/java/com/thealgorithms/backtracking/WordPatternMatcher.java
package com.thealgorithms.backtracking; import java.util.HashMap; import java.util.Map; /** * Class to determine if a pattern matches a string using backtracking. * * Example: * Pattern: "abab" * Input String: "JavaPythonJavaPython" * Output: true * * Pattern: "aaaa" * Input String: "JavaJavaJavaJava" * Output: true * * Pattern: "aabb" * Input String: "JavaPythonPythonJava" * Output: false */ public final class WordPatternMatcher { private WordPatternMatcher() { } /** * Determines if the given pattern matches the input string using backtracking. * * @param pattern The pattern to match. * @param inputString The string to match against the pattern. * @return True if the pattern matches the string, False otherwise. */ public static boolean matchWordPattern(String pattern, String inputString) { Map<Character, String> patternMap = new HashMap<>(); Map<String, Character> strMap = new HashMap<>(); return backtrack(pattern, inputString, 0, 0, patternMap, strMap); } /** * Backtracking helper function to check if the pattern matches the string. * * @param pattern The pattern string. * @param inputString The string to match against the pattern. * @param patternIndex Current index in the pattern. * @param strIndex Current index in the input string. * @param patternMap Map to store pattern characters to string mappings. * @param strMap Map to store string to pattern character mappings. * @return True if the pattern matches, False otherwise. */ private static boolean backtrack(String pattern, String inputString, int patternIndex, int strIndex, Map<Character, String> patternMap, Map<String, Character> strMap) { if (patternIndex == pattern.length() && strIndex == inputString.length()) { return true; } if (patternIndex == pattern.length() || strIndex == inputString.length()) { return false; } char currentChar = pattern.charAt(patternIndex); if (patternMap.containsKey(currentChar)) { String mappedStr = patternMap.get(currentChar); if (inputString.startsWith(mappedStr, strIndex)) { return backtrack(pattern, inputString, patternIndex + 1, strIndex + mappedStr.length(), patternMap, strMap); } else { return false; } } for (int end = strIndex + 1; end <= inputString.length(); end++) { String substring = inputString.substring(strIndex, end); if (strMap.containsKey(substring)) { continue; } patternMap.put(currentChar, substring); strMap.put(substring, currentChar); if (backtrack(pattern, inputString, patternIndex + 1, end, patternMap, strMap)) { return true; } patternMap.remove(currentChar); strMap.remove(substring); } 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/backtracking/UniquePermutation.java
src/main/java/com/thealgorithms/backtracking/UniquePermutation.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Generates all UNIQUE permutations of a string, even when duplicate characters exist. * * Example: * Input: "AAB" * Output: ["AAB", "ABA", "BAA"] * * Time Complexity: O(n! * n) */ public final class UniquePermutation { private UniquePermutation() { // Prevent instantiation throw new UnsupportedOperationException("Utility class"); } public static List<String> generateUniquePermutations(String input) { List<String> result = new ArrayList<>(); if (input == null) { return result; } char[] chars = input.toCharArray(); Arrays.sort(chars); // important: sort to detect duplicates backtrack(chars, new boolean[chars.length], new StringBuilder(), result); return result; } private static void backtrack(char[] chars, boolean[] used, StringBuilder current, List<String> result) { if (current.length() == chars.length) { result.add(current.toString()); return; } for (int i = 0; i < chars.length; i++) { // skip duplicates if (i > 0 && chars[i] == chars[i - 1] && !used[i - 1]) { continue; } if (!used[i]) { used[i] = true; current.append(chars[i]); backtrack(chars, used, current, result); // undo changes used[i] = false; current.deleteCharAt(current.length() - 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/backtracking/NQueens.java
src/main/java/com/thealgorithms/backtracking/NQueens.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.List; /** * Problem statement: Given a N x N chess board. Return all arrangements in * which N queens can be placed on the board such no two queens attack each * other. Ex. N = 6 Solution= There are 4 possible ways Arrangement: 1 ".Q....", * "...Q..", ".....Q", "Q.....", "..Q...", "....Q." * * Arrangement: 2 "..Q...", ".....Q", ".Q....", "....Q.", "Q.....", "...Q.." * * Arrangement: 3 "...Q..", "Q.....", "....Q.", ".Q....", ".....Q", "..Q..." * * Arrangement: 4 "....Q.", "..Q...", "Q.....", ".....Q", "...Q..", ".Q...." * * Solution: Brute Force approach: * * Generate all possible arrangement to place N queens on N*N board. Check each * board if queens are placed safely. If it is safe, include arrangement in * solution set. Otherwise, ignore it * * Optimized solution: This can be solved using backtracking in below steps * * Start with first column and place queen on first row Try placing queen in a * row on second column If placing second queen in second column attacks any of * the previous queens, change the row in second column otherwise move to next * column and try to place next queen In case if there is no rows where a queen * can be placed such that it doesn't attack previous queens, then go back to * previous column and change row of previous queen. Keep doing this until last * queen is not placed safely. If there is no such way then return an empty list * as solution */ public final class NQueens { private NQueens() { } public static List<List<String>> getNQueensArrangements(int queens) { List<List<String>> arrangements = new ArrayList<>(); getSolution(queens, arrangements, new int[queens], 0); return arrangements; } public static void placeQueens(final int queens) { List<List<String>> arrangements = new ArrayList<List<String>>(); getSolution(queens, arrangements, new int[queens], 0); if (arrangements.isEmpty()) { System.out.println("There is no way to place " + queens + " queens on board of size " + queens + "x" + queens); } else { System.out.println("Arrangement for placing " + queens + " queens"); } for (List<String> arrangement : arrangements) { arrangement.forEach(System.out::println); System.out.println(); } } /** * This is backtracking function which tries to place queen recursively * * @param boardSize: size of chess board * @param solutions: this holds all possible arrangements * @param columns: columns[i] = rowId where queen is placed in ith column. * @param columnIndex: This is the column in which queen is being placed */ private static void getSolution(int boardSize, List<List<String>> solutions, int[] columns, int columnIndex) { if (columnIndex == boardSize) { // this means that all queens have been placed List<String> sol = new ArrayList<String>(); for (int i = 0; i < boardSize; i++) { StringBuilder sb = new StringBuilder(); for (int j = 0; j < boardSize; j++) { sb.append(j == columns[i] ? "Q" : "."); } sol.add(sb.toString()); } solutions.add(sol); return; } // This loop tries to place queen in a row one by one for (int rowIndex = 0; rowIndex < boardSize; rowIndex++) { columns[columnIndex] = rowIndex; if (isPlacedCorrectly(columns, rowIndex, columnIndex)) { // If queen is placed successfully at rowIndex in column=columnIndex then try // placing queen in next column getSolution(boardSize, solutions, columns, columnIndex + 1); } } } /** * This function checks if queen can be placed at row = rowIndex in column = * columnIndex safely * * @param columns: columns[i] = rowId where queen is placed in ith column. * @param rowIndex: row in which queen has to be placed * @param columnIndex: column in which queen is being placed * @return true: if queen can be placed safely false: otherwise */ private static boolean isPlacedCorrectly(int[] columns, int rowIndex, int columnIndex) { for (int i = 0; i < columnIndex; i++) { int diff = Math.abs(columns[i] - rowIndex); if (diff == 0 || columnIndex - i == diff) { 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/backtracking/WordSearch.java
src/main/java/com/thealgorithms/backtracking/WordSearch.java
package com.thealgorithms.backtracking; /** * Word Search Problem * * This class solves the word search problem where given an m x n grid of characters (board) * and a target word, the task is to check if the word exists in the grid. * The word can be constructed from sequentially adjacent cells (horizontally or vertically), * and the same cell may not be used more than once in constructing the word. * * Example: * - For board = * [ * ['A','B','C','E'], * ['S','F','C','S'], * ['A','D','E','E'] * ] * and word = "ABCCED", -> returns true * and word = "SEE", -> returns true * and word = "ABCB", -> returns false * * Solution: * - Depth First Search (DFS) with backtracking is used to explore possible paths from any cell * matching the first letter of the word. DFS ensures that we search all valid paths, while * backtracking helps in reverting decisions when a path fails to lead to a solution. * * Time Complexity: O(m * n * 3^L) * - m = number of rows in the board * - n = number of columns in the board * - L = length of the word * - For each cell, we look at 3 possible directions (since we exclude the previously visited direction), * and we do this for L letters. * * Space Complexity: O(L) * - Stack space for the recursive DFS function, where L is the maximum depth of recursion (length of the word). */ public class WordSearch { private final int[] dx = {0, 0, 1, -1}; private final int[] dy = {1, -1, 0, 0}; private boolean[][] visited; private char[][] board; private String word; /** * Checks if the given (x, y) coordinates are valid positions in the board. * * @param x The row index. * @param y The column index. * @return True if the coordinates are within the bounds of the board; false otherwise. */ private boolean isValid(int x, int y) { return x >= 0 && x < board.length && y >= 0 && y < board[0].length; } /** * Performs Depth First Search (DFS) from the cell (x, y) * to search for the next character in the word. * * @param x The current row index. * @param y The current column index. * @param nextIdx The index of the next character in the word to be matched. * @return True if a valid path is found to match the remaining characters of the word; false otherwise. */ private boolean doDFS(int x, int y, int nextIdx) { visited[x][y] = true; if (nextIdx == word.length()) { return true; } for (int i = 0; i < 4; ++i) { int xi = x + dx[i]; int yi = y + dy[i]; if (isValid(xi, yi) && board[xi][yi] == word.charAt(nextIdx) && !visited[xi][yi]) { boolean exists = doDFS(xi, yi, nextIdx + 1); if (exists) { return true; } } } visited[x][y] = false; // Backtrack return false; } /** * Main function to check if the word exists in the board. It initiates DFS from any * cell that matches the first character of the word. * * @param board The 2D grid of characters (the board). * @param word The target word to search for in the board. * @return True if the word exists in the board; false otherwise. */ public boolean exist(char[][] board, String word) { this.board = board; this.word = word; for (int i = 0; i < board.length; ++i) { for (int j = 0; j < board[0].length; ++j) { if (board[i][j] == word.charAt(0)) { visited = new boolean[board.length][board[0].length]; boolean exists = doDFS(i, j, 1); if (exists) { 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/backtracking/CombinationSum.java
src/main/java/com/thealgorithms/backtracking/CombinationSum.java
package com.thealgorithms.backtracking; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** Backtracking: pick/not-pick with reuse of candidates. */ public final class CombinationSum { private CombinationSum() { throw new UnsupportedOperationException("Utility class"); } public static List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> results = new ArrayList<>(); if (candidates == null || candidates.length == 0) { return results; } // Sort to help with pruning duplicates and early termination Arrays.sort(candidates); backtrack(candidates, target, 0, new ArrayList<>(), results); return results; } private static void backtrack(int[] candidates, int remaining, int start, List<Integer> combination, List<List<Integer>> results) { if (remaining == 0) { // Found valid combination; add a copy results.add(new ArrayList<>(combination)); return; } for (int i = start; i < candidates.length; i++) { int candidate = candidates[i]; // If candidate is greater than remaining target, further candidates (sorted) will also be too big if (candidate > remaining) { break; } // include candidate combination.add(candidate); // Because we can reuse the same element, we pass i (not i + 1) backtrack(candidates, remaining - candidate, i, combination, results); // backtrack: remove last combination.remove(combination.size() - 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/backtracking/MazeRecursion.java
src/main/java/com/thealgorithms/backtracking/MazeRecursion.java
package com.thealgorithms.backtracking; /** * This class contains methods to solve a maze using recursive backtracking. * The maze is represented as a 2D array where walls, paths, and visited/dead * ends are marked with different integers. * * The goal is to find a path from a starting position to the target position * (map[6][5]) while navigating through the maze. */ public final class MazeRecursion { private MazeRecursion() { } /** * This method solves the maze using the "down -> right -> up -> left" * movement strategy. * * @param map The 2D array representing the maze (walls, paths, etc.) * @return The solved maze with paths marked, or null if no solution exists. */ public static int[][] solveMazeUsingFirstStrategy(int[][] map) { if (setWay(map, 1, 1)) { return map; } return null; } /** * This method solves the maze using the "up -> right -> down -> left" * movement strategy. * * @param map The 2D array representing the maze (walls, paths, etc.) * @return The solved maze with paths marked, or null if no solution exists. */ public static int[][] solveMazeUsingSecondStrategy(int[][] map) { if (setWay2(map, 1, 1)) { return map; } return null; } /** * Attempts to find a path through the maze using a "down -> right -> up -> left" * movement strategy. The path is marked with '2' for valid paths and '3' for dead ends. * * @param map The 2D array representing the maze (walls, paths, etc.) * @param i The current x-coordinate of the ball (row index) * @param j The current y-coordinate of the ball (column index) * @return True if a path is found to (6,5), otherwise false */ private static boolean setWay(int[][] map, int i, int j) { if (map[6][5] == 2) { return true; } // If the current position is unvisited (0), explore it if (map[i][j] == 0) { // Mark the current position as '2' map[i][j] = 2; // Move down if (setWay(map, i + 1, j)) { return true; } // Move right else if (setWay(map, i, j + 1)) { return true; } // Move up else if (setWay(map, i - 1, j)) { return true; } // Move left else if (setWay(map, i, j - 1)) { return true; } map[i][j] = 3; // Mark as dead end (3) if no direction worked return false; } return false; } /** * Attempts to find a path through the maze using an alternative movement * strategy "up -> right -> down -> left". * * @param map The 2D array representing the maze (walls, paths, etc.) * @param i The current x-coordinate of the ball (row index) * @param j The current y-coordinate of the ball (column index) * @return True if a path is found to (6,5), otherwise false */ private static boolean setWay2(int[][] map, int i, int j) { if (map[6][5] == 2) { return true; } if (map[i][j] == 0) { map[i][j] = 2; // Move up if (setWay2(map, i - 1, j)) { return true; } // Move right else if (setWay2(map, i, j + 1)) { return true; } // Move down else if (setWay2(map, i + 1, j)) { return true; } // Move left else if (setWay2(map, i, j - 1)) { return true; } map[i][j] = 3; // Mark as dead end (3) if no direction worked return false; } 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/physics/DampedOscillator.java
src/main/java/com/thealgorithms/physics/DampedOscillator.java
package com.thealgorithms.physics; /** * Models a damped harmonic oscillator, capturing the behavior of a mass-spring-damper system. * * <p>The system is defined by the second-order differential equation: * x'' + 2 * gamma * x' + omega₀² * x = 0 * where: * <ul> * <li><b>omega₀</b> is the natural (undamped) angular frequency in radians per second.</li> * <li><b>gamma</b> is the damping coefficient in inverse seconds.</li> * </ul> * * <p>This implementation provides: * <ul> * <li>An analytical solution for the underdamped case (γ < ω₀).</li> * <li>A numerical integrator based on the explicit Euler method for simulation purposes.</li> * </ul> * * <p><strong>Usage Example:</strong> * <pre>{@code * DampedOscillator oscillator = new DampedOscillator(10.0, 0.5); * double displacement = oscillator.displacementAnalytical(1.0, 0.0, 0.1); * double[] nextState = oscillator.stepEuler(new double[]{1.0, 0.0}, 0.001); * }</pre> * * @author [Yash Rajput](https://github.com/the-yash-rajput) */ public final class DampedOscillator { /** Natural (undamped) angular frequency (rad/s). */ private final double omega0; /** Damping coefficient (s⁻¹). */ private final double gamma; private DampedOscillator() { throw new AssertionError("No instances."); } /** * Constructs a damped oscillator model. * * @param omega0 the natural frequency (rad/s), must be positive * @param gamma the damping coefficient (s⁻¹), must be non-negative * @throws IllegalArgumentException if parameters are invalid */ public DampedOscillator(double omega0, double gamma) { if (omega0 <= 0) { throw new IllegalArgumentException("Natural frequency must be positive."); } if (gamma < 0) { throw new IllegalArgumentException("Damping coefficient must be non-negative."); } this.omega0 = omega0; this.gamma = gamma; } /** * Computes the analytical displacement of an underdamped oscillator. * Formula: x(t) = A * exp(-γt) * cos(ω_d t + φ) * * @param amplitude the initial amplitude A * @param phase the initial phase φ (radians) * @param time the time t (seconds) * @return the displacement x(t) */ public double displacementAnalytical(double amplitude, double phase, double time) { double omegaD = Math.sqrt(Math.max(0.0, omega0 * omega0 - gamma * gamma)); return amplitude * Math.exp(-gamma * time) * Math.cos(omegaD * time + phase); } /** * Performs a single integration step using the explicit Euler method. * State vector format: [x, v], where v = dx/dt. * * @param state the current state [x, v] * @param dt the time step (seconds) * @return the next state [x_next, v_next] * @throws IllegalArgumentException if the state array is invalid or dt is non-positive */ public double[] stepEuler(double[] state, double dt) { if (state == null || state.length != 2) { throw new IllegalArgumentException("State must be a non-null array of length 2."); } if (dt <= 0) { throw new IllegalArgumentException("Time step must be positive."); } double x = state[0]; double v = state[1]; double acceleration = -2.0 * gamma * v - omega0 * omega0 * x; double xNext = x + dt * v; double vNext = v + dt * acceleration; return new double[] {xNext, vNext}; } /** @return the natural (undamped) angular frequency (rad/s). */ public double getOmega0() { return omega0; } /** @return the damping coefficient (s⁻¹). */ public double getGamma() { return gamma; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java
src/main/java/com/thealgorithms/physics/GroundToGroundProjectileMotion.java
package com.thealgorithms.physics; /** * Ground to ground projectile motion calculator * * Ground to ground projectile motion is when a projectile's trajectory * starts at the ground, reaches the apex, then falls back on the ground. * * @author [Yash Rajput](https://github.com/the-yash-rajput) */ public final class GroundToGroundProjectileMotion { private GroundToGroundProjectileMotion() { throw new AssertionError("No instances."); } /** Standard gravity constant (m/s^2) */ private static final double GRAVITY = 9.80665; /** * Convert degrees to radians * * @param degrees Angle in degrees * @return Angle in radians */ private static double degreesToRadians(double degrees) { return degrees * (Math.PI / 180.0); } /** * Calculate the time of flight * * @param initialVelocity The starting velocity of the projectile (m/s) * @param angle The angle that the projectile is launched at in degrees * @return The time that the projectile is in the air for (seconds) */ public static double timeOfFlight(double initialVelocity, double angle) { return timeOfFlight(initialVelocity, angle, GRAVITY); } /** * Calculate the time of flight with custom gravity * * @param initialVelocity The starting velocity of the projectile (m/s) * @param angle The angle that the projectile is launched at in degrees * @param gravity The value used for the gravity constant (m/s^2) * @return The time that the projectile is in the air for (seconds) */ public static double timeOfFlight(double initialVelocity, double angle, double gravity) { double viy = initialVelocity * Math.sin(degreesToRadians(angle)); return 2.0 * viy / gravity; } /** * Calculate the horizontal distance that the projectile travels * * @param initialVelocity The starting velocity of the projectile (m/s) * @param angle The angle that the projectile is launched at in degrees * @param time The time that the projectile is in the air (seconds) * @return Horizontal distance that the projectile travels (meters) */ public static double horizontalRange(double initialVelocity, double angle, double time) { double vix = initialVelocity * Math.cos(degreesToRadians(angle)); return vix * time; } /** * Calculate the max height of the projectile * * @param initialVelocity The starting velocity of the projectile (m/s) * @param angle The angle that the projectile is launched at in degrees * @return The max height that the projectile reaches (meters) */ public static double maxHeight(double initialVelocity, double angle) { return maxHeight(initialVelocity, angle, GRAVITY); } /** * Calculate the max height of the projectile with custom gravity * * @param initialVelocity The starting velocity of the projectile (m/s) * @param angle The angle that the projectile is launched at in degrees * @param gravity The value used for the gravity constant (m/s^2) * @return The max height that the projectile reaches (meters) */ public static double maxHeight(double initialVelocity, double angle, double gravity) { double viy = initialVelocity * Math.sin(degreesToRadians(angle)); return Math.pow(viy, 2) / (2.0 * gravity); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/ThinLens.java
src/main/java/com/thealgorithms/physics/ThinLens.java
package com.thealgorithms.physics; /** * Implements the Thin Lens Formula used in ray optics: * * <pre> * 1/f = 1/v + 1/u * </pre> * * where: * <ul> * <li>f = focal length</li> * <li>u = object distance</li> * <li>v = image distance</li> * </ul> * * Uses the Cartesian sign convention. * * @see <a href="https://en.wikipedia.org/wiki/Thin_lens">Thin Lens</a> */ public final class ThinLens { private ThinLens() { throw new AssertionError("No instances."); } /** * Computes the image distance using the thin lens formula. * * @param focalLength focal length of the lens (f) * @param objectDistance object distance (u) * @return image distance (v) * @throws IllegalArgumentException if focal length or object distance is zero */ public static double imageDistance(double focalLength, double objectDistance) { if (focalLength == 0 || objectDistance == 0) { throw new IllegalArgumentException("Focal length and object distance must be non-zero."); } return 1.0 / ((1.0 / focalLength) - (1.0 / objectDistance)); } /** * Computes magnification of the image. * * <pre> * m = v / u * </pre> * * @param imageDistance image distance (v) * @param objectDistance object distance (u) * @return magnification * @throws IllegalArgumentException if object distance is zero */ public static double magnification(double imageDistance, double objectDistance) { if (objectDistance == 0) { throw new IllegalArgumentException("Object distance must be non-zero."); } return imageDistance / objectDistance; } /** * Determines whether the image formed is real or virtual. * * @param imageDistance image distance (v) * @return {@code true} if image is real, {@code false} if virtual */ public static boolean isRealImage(double imageDistance) { return imageDistance > 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/physics/SimplePendulumRK4.java
src/main/java/com/thealgorithms/physics/SimplePendulumRK4.java
package com.thealgorithms.physics; /** * Simulates a simple pendulum using the Runge-Kutta 4th order method. * The pendulum is modeled with the nonlinear differential equation. * * @author [Yash Rajput](https://github.com/the-yash-rajput) */ public final class SimplePendulumRK4 { private SimplePendulumRK4() { throw new AssertionError("No instances."); } private final double length; // meters private final double g; // acceleration due to gravity (m/s^2) /** * Constructs a simple pendulum simulator. * * @param length the length of the pendulum in meters * @param g the acceleration due to gravity in m/s^2 */ public SimplePendulumRK4(double length, double g) { if (length <= 0) { throw new IllegalArgumentException("Length must be positive"); } if (g <= 0) { throw new IllegalArgumentException("Gravity must be positive"); } this.length = length; this.g = g; } /** * Computes the derivatives of the state vector. * State: [theta, omega] where theta is angle and omega is angular velocity. * * @param state the current state [theta, omega] * @return the derivatives [dtheta/dt, domega/dt] */ private double[] derivatives(double[] state) { double theta = state[0]; double omega = state[1]; double dtheta = omega; double domega = -(g / length) * Math.sin(theta); return new double[] {dtheta, domega}; } /** * Performs one time step using the RK4 method. * * @param state the current state [theta, omega] * @param dt the time step size * @return the new state after time dt */ public double[] stepRK4(double[] state, double dt) { if (state == null || state.length != 2) { throw new IllegalArgumentException("State must be array of length 2"); } if (dt <= 0) { throw new IllegalArgumentException("Time step must be positive"); } double[] k1 = derivatives(state); double[] s2 = new double[] {state[0] + 0.5 * dt * k1[0], state[1] + 0.5 * dt * k1[1]}; double[] k2 = derivatives(s2); double[] s3 = new double[] {state[0] + 0.5 * dt * k2[0], state[1] + 0.5 * dt * k2[1]}; double[] k3 = derivatives(s3); double[] s4 = new double[] {state[0] + dt * k3[0], state[1] + dt * k3[1]}; double[] k4 = derivatives(s4); double thetaNext = state[0] + dt / 6.0 * (k1[0] + 2 * k2[0] + 2 * k3[0] + k4[0]); double omegaNext = state[1] + dt / 6.0 * (k1[1] + 2 * k2[1] + 2 * k3[1] + k4[1]); return new double[] {thetaNext, omegaNext}; } /** * Simulates the pendulum for a given duration. * * @param initialState the initial state [theta, omega] * @param dt the time step size * @param steps the number of steps to simulate * @return array of states at each step */ public double[][] simulate(double[] initialState, double dt, int steps) { double[][] trajectory = new double[steps + 1][2]; trajectory[0] = initialState.clone(); double[] currentState = initialState.clone(); for (int i = 1; i <= steps; i++) { currentState = stepRK4(currentState, dt); trajectory[i] = currentState.clone(); } return trajectory; } /** * Calculates the total energy of the pendulum. * E = (1/2) * m * L^2 * omega^2 + m * g * L * (1 - cos(theta)) * We use m = 1 for simplicity. * * @param state the current state [theta, omega] * @return the total energy */ public double calculateEnergy(double[] state) { double theta = state[0]; double omega = state[1]; double kineticEnergy = 0.5 * length * length * omega * omega; double potentialEnergy = g * length * (1 - Math.cos(theta)); return kineticEnergy + potentialEnergy; } public double getLength() { return length; } public double getGravity() { return g; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/Kinematics.java
src/main/java/com/thealgorithms/physics/Kinematics.java
package com.thealgorithms.physics; /** * Implements the fundamental "SUVAT" equations for motion * under constant acceleration. * * @author [Priyanshu Kumar Singh](https://github.com/Priyanshu1303d) * @see <a href="https://en.wikipedia.org/wiki/Equations_of_motion#Uniform_acceleration">Wikipedia</a> */ public final class Kinematics { private Kinematics() { } /** * Calculates the final velocity (v) of an object. * Formula: v = u + at * * @param u Initial velocity (m/s). * @param a Constant acceleration (m/s^2). * @param t Time elapsed (s). * @return The final velocity (m/s). */ public static double calculateFinalVelocity(double u, double a, double t) { return u + a * t; } /** * Calculates the displacement (s) of an object. * Formula: s = ut + 0.5 * a * t^2 * * @param u Initial velocity (m/s). * @param a Constant acceleration (m/s^2). * @param t Time elapsed (s). * @return The displacement (m). */ public static double calculateDisplacement(double u, double a, double t) { return u * t + 0.5 * a * t * t; } /** * Calculates the displacement (s) of an object. * Formula: v^2 = u^2 + 2 * a * s * * @param u Initial velocity (m/s). * @param a Constant acceleration (m/s^2). * @param s Displacement (m). * @return The final velocity squared (m/s)^2. */ public static double calculateFinalVelocitySquared(double u, double a, double s) { return u * u + 2 * a * s; } /** * Calculates the displacement (s) using the average velocity. * Formula: s = (u + v) / 2 * t * * @param u Initial velocity (m/s). * @param v Final velocity (m/s). * @param t Time elapsed (s). * @return The displacement (m). */ public static double calculateDisplacementFromVelocities(double u, double v, double t) { double velocitySum = u + v; return velocitySum / 2 * t; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/Gravitation.java
src/main/java/com/thealgorithms/physics/Gravitation.java
package com.thealgorithms.physics; /** * Implements Newton's Law of Universal Gravitation. * Provides simple static methods to calculate gravitational force and circular orbit velocity. * * @author [Priyanshu Kumar Singh](https://github.com/Priyanshu1303d) * @see <a href="https://en.wikipedia.org/wiki/Newton%27s_law_of_universal_gravitation">Wikipedia</a> */ public final class Gravitation { /** Gravitational constant in m^3 kg^-1 s^-2 */ public static final double GRAVITATIONAL_CONSTANT = 6.67430e-11; /** * Private constructor to prevent instantiation of this utility class. */ private Gravitation() { } /** * Calculates the gravitational force vector exerted by one body on another. * * @param m1 Mass of the first body (kg). * @param x1 X-position of the first body (m). * @param y1 Y-position of the first body (m). * @param m2 Mass of the second body (kg). * @param x2 X-position of the second body (m). * @param y2 Y-position of the second body (m). * @return A double array `[fx, fy]` representing the force vector on the second body. */ public static double[] calculateGravitationalForce(double m1, double x1, double y1, double m2, double x2, double y2) { double dx = x1 - x2; double dy = y1 - y2; double distanceSq = dx * dx + dy * dy; // If bodies are at the same position, force is zero to avoid division by zero. if (distanceSq == 0) { return new double[] {0, 0}; } double distance = Math.sqrt(distanceSq); double forceMagnitude = GRAVITATIONAL_CONSTANT * m1 * m2 / distanceSq; // Calculate the components of the force vector double fx = forceMagnitude * (dx / distance); double fy = forceMagnitude * (dy / distance); return new double[] {fx, fy}; } /** * Calculates the speed required for a stable circular orbit. * * @param centralMass The mass of the central body (kg). * @param radius The radius of the orbit (m). * @return The orbital speed (m/s). * @throws IllegalArgumentException if mass or radius are not positive. */ public static double calculateCircularOrbitVelocity(double centralMass, double radius) { if (centralMass <= 0 || radius <= 0) { throw new IllegalArgumentException("Mass and radius must be positive."); } return Math.sqrt(GRAVITATIONAL_CONSTANT * centralMass / radius); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/SnellLaw.java
src/main/java/com/thealgorithms/physics/SnellLaw.java
package com.thealgorithms.physics; /** * Calculates refraction angle using Snell's Law: * n1 * sin(theta1) = n2 * sin(theta2) * @see <a href="https://en.wikipedia.org/wiki/Snell%27s_law">Snell's Law</a> */ public final class SnellLaw { private SnellLaw() { throw new AssertionError("No instances."); } /** * Computes the refracted angle (theta2) in radians. * * @param n1 index of refraction of medium 1 * @param n2 index of refraction of medium 2 * @param theta1 incident angle in radians * @return refracted angle (theta2) in radians * @throws IllegalArgumentException if total internal reflection occurs */ public static double refractedAngle(double n1, double n2, double theta1) { double ratio = n1 / n2; double sinTheta2 = ratio * Math.sin(theta1); if (Math.abs(sinTheta2) > 1.0) { throw new IllegalArgumentException("Total internal reflection: no refraction possible."); } return Math.asin(sinTheta2); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/ElasticCollision2D.java
src/main/java/com/thealgorithms/physics/ElasticCollision2D.java
package com.thealgorithms.physics; /** * 2D Elastic collision between two circular bodies * Based on principles of conservation of momentum and kinetic energy. * * @author [Yash Rajput](https://github.com/the-yash-rajput) */ public final class ElasticCollision2D { private ElasticCollision2D() { throw new AssertionError("No instances. Utility class"); } public static class Body { public double x; public double y; public double vx; public double vy; public double mass; public double radius; public Body(double x, double y, double vx, double vy, double mass, double radius) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.mass = mass; this.radius = radius; } } /** * Resolve instantaneous elastic collision between two circular bodies. * * @param a first body * @param b second body */ public static void resolveCollision(Body a, Body b) { double dx = b.x - a.x; double dy = b.y - a.y; double dist = Math.hypot(dx, dy); if (dist == 0) { return; // overlapping } double nx = dx / dist; double ny = dy / dist; // relative velocity along normal double rv = (b.vx - a.vx) * nx + (b.vy - a.vy) * ny; if (rv > 0) { return; // moving apart } // impulse with masses double m1 = a.mass; double m2 = b.mass; double j = -(1 + 1.0) * rv / (1.0 / m1 + 1.0 / m2); // impulse vector double impulseX = j * nx; double impulseY = j * ny; a.vx -= impulseX / m1; a.vy -= impulseY / m1; b.vx += impulseX / m2; b.vy += impulseY / m2; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/ProjectileMotion.java
src/main/java/com/thealgorithms/physics/ProjectileMotion.java
package com.thealgorithms.physics; /** * * This implementation calculates the flight path of a projectile launched from any INITIAL HEIGHT. * It is a more flexible version of the ground-to-ground model. * * @see <a href="https://en.wikipedia.org/wiki/Projectile_motion">Wikipedia - Projectile Motion</a> * @author [Priyanshu Kumar Singh](https://github.com/Priyanshu1303d) */ public final class ProjectileMotion { private ProjectileMotion() { } /** Standard Earth gravity constant*/ private static final double GRAVITY = 9.80665; /** * A simple container for the results of a projectile motion calculation. */ public static final class Result { private final double timeOfFlight; private final double horizontalRange; private final double maxHeight; public Result(double timeOfFlight, double horizontalRange, double maxHeight) { this.timeOfFlight = timeOfFlight; this.horizontalRange = horizontalRange; this.maxHeight = maxHeight; } /** @return The total time the projectile is in the air (seconds). */ public double getTimeOfFlight() { return timeOfFlight; } /** @return The total horizontal distance traveled (meters). */ public double getHorizontalRange() { return horizontalRange; } /** @return The maximum vertical height from the ground (meters). */ public double getMaxHeight() { return maxHeight; } } /** * Calculates projectile trajectory using standard Earth gravity. * * @param initialVelocity Initial speed of the projectile (m/s). * @param launchAngleDegrees Launch angle from the horizontal (degrees). * @param initialHeight Starting height of the projectile (m). * @return A {@link Result} object with the trajectory data. */ public static Result calculateTrajectory(double initialVelocity, double launchAngleDegrees, double initialHeight) { return calculateTrajectory(initialVelocity, launchAngleDegrees, initialHeight, GRAVITY); } /** * Calculates projectile trajectory with a custom gravity value. * * @param initialVelocity Initial speed (m/s). Must be non-negative. * @param launchAngleDegrees Launch angle (degrees). * @param initialHeight Starting height (m). Must be non-negative. * @param gravity Acceleration due to gravity (m/s^2). Must be positive. * @return A {@link Result} object with the trajectory data. */ public static Result calculateTrajectory(double initialVelocity, double launchAngleDegrees, double initialHeight, double gravity) { if (initialVelocity < 0 || initialHeight < 0 || gravity <= 0) { throw new IllegalArgumentException("Velocity, height, and gravity must be non-negative, and gravity must be positive."); } double launchAngleRadians = Math.toRadians(launchAngleDegrees); double initialVerticalVelocity = initialVelocity * Math.sin(launchAngleRadians); // Initial vertical velocity double initialHorizontalVelocity = initialVelocity * Math.cos(launchAngleRadians); // Initial horizontal velocity // Correctly calculate total time of flight using the quadratic formula for vertical motion. // y(t) = y0 + initialVerticalVelocity*t - 0.5*g*t^2. We solve for t when y(t) = 0. double totalTimeOfFlight = (initialVerticalVelocity + Math.sqrt(initialVerticalVelocity * initialVerticalVelocity + 2 * gravity * initialHeight)) / gravity; // Calculate max height. If launched downwards, max height is the initial height. double maxHeight; if (initialVerticalVelocity > 0) { double heightGained = initialVerticalVelocity * initialVerticalVelocity / (2 * gravity); maxHeight = initialHeight + heightGained; } else { maxHeight = initialHeight; } double horizontalRange = initialHorizontalVelocity * totalTimeOfFlight; return new Result(totalTimeOfFlight, horizontalRange, maxHeight); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/physics/CoulombsLaw.java
src/main/java/com/thealgorithms/physics/CoulombsLaw.java
package com.thealgorithms.physics; /** * Implements Coulomb's Law for electrostatics. * Provides simple static methods to calculate electrostatic force and circular orbit velocity. * * @author [Priyanshu Singh](https://github.com/Priyanshu1303d) * @see <a href="https://en.wikipedia.org/wiki/Coulomb%27s_law">Wikipedia</a> */ public final class CoulombsLaw { /** Coulomb's constant in N·m²/C² */ public static final double COULOMBS_CONSTANT = 8.9875517923e9; /** * Private constructor to prevent instantiation of this utility class. */ private CoulombsLaw() { } /** * Calculates the electrostatic force vector exerted by one charge on another. * The returned vector is the force *on* the second charge (q2). * * @param q1 Charge of the first particle (in Coulombs). * @param x1 X-position of the first particle (m). * @param y1 Y-position of the first particle (m). * @param q2 Charge of the second particle (in Coulombs). * @param x2 X-position of the second particle (m). * @param y2 Y-position of the second particle (m). * @return A double array `[fx, fy]` representing the force vector on the second charge. */ public static double[] calculateForceVector(double q1, double x1, double y1, double q2, double x2, double y2) { // Vector from 1 to 2 double dx = x2 - x1; double dy = y2 - y1; double distanceSq = dx * dx + dy * dy; // If particles are at the same position, force is zero to avoid division by zero. if (distanceSq == 0) { return new double[] {0, 0}; } double distance = Math.sqrt(distanceSq); // Force magnitude: k * (q1 * q2) / r^2 // A positive result is repulsive (pushes q2 away from q1). // A negative result is attractive (pulls q2 toward q1). double forceMagnitude = COULOMBS_CONSTANT * q1 * q2 / distanceSq; // Calculate the components of the force vector // (dx / distance) is the unit vector pointing from 1 to 2. double fx = forceMagnitude * (dx / distance); double fy = forceMagnitude * (dy / distance); return new double[] {fx, fy}; } /** * Calculates the speed required for a stable circular orbit of a charged particle * around a central charge (e.g., an electron orbiting a nucleus). * * @param centralCharge The charge of the central body (in Coulombs). * @param orbitingCharge The charge of the orbiting body (in Coulombs). * @param orbitingMass The mass of the orbiting body (in kg). * @param radius The radius of the orbit (in m). * @return The orbital speed (in m/s). * @throws IllegalArgumentException if mass or radius are not positive. */ public static double calculateCircularOrbitVelocity(double centralCharge, double orbitingCharge, double orbitingMass, double radius) { if (orbitingMass <= 0 || radius <= 0) { throw new IllegalArgumentException("Orbiting mass and radius must be positive."); } // We only need the magnitude of the force, which is always positive. double forceMagnitude = Math.abs(COULOMBS_CONSTANT * centralCharge * orbitingCharge) / (radius * radius); // F_c = m * v^2 / r => v = sqrt(F_c * r / m) return Math.sqrt(forceMagnitude * radius / orbitingMass); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java
src/main/java/com/thealgorithms/misc/PalindromeSinglyLinkedList.java
package com.thealgorithms.misc; import java.util.Stack; /** * A simple way of knowing if a singly linked list is palindrome is to push all * the values into a Stack and then compare the list to popped vales from the * Stack. * * See more: * https://www.geeksforgeeks.org/function-to-check-if-a-singly-linked-list-is-palindrome/ */ @SuppressWarnings("rawtypes") public final class PalindromeSinglyLinkedList { private PalindromeSinglyLinkedList() { } public static boolean isPalindrome(final Iterable linkedList) { var linkedListValues = new Stack<>(); for (final var x : linkedList) { linkedListValues.push(x); } for (final var x : linkedList) { if (x != linkedListValues.pop()) { return false; } } return true; } // Optimised approach with O(n) time complexity and O(1) space complexity public static boolean isPalindromeOptimised(Node head) { if (head == null || head.next == null) { return true; } Node slow = head; Node fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } Node midNode = slow; Node prevNode = null; Node currNode = midNode; Node nextNode; while (currNode != null) { nextNode = currNode.next; currNode.next = prevNode; prevNode = currNode; currNode = nextNode; } Node left = head; Node right = prevNode; while (left != null && right != null) { if (left.val != right.val) { return false; } right = right.next; left = left.next; } return true; } static class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java
package com.thealgorithms.misc; public final class MedianOfRunningArrayInteger extends MedianOfRunningArray<Integer> { @Override public Integer calculateAverage(final Integer a, final Integer b) { return (a + b) / 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/misc/ThreeSumProblem.java
src/main/java/com/thealgorithms/misc/ThreeSumProblem.java
package com.thealgorithms.misc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class ThreeSumProblem { public List<List<Integer>> bruteForce(int[] nums, int target) { List<List<Integer>> arr = new ArrayList<List<Integer>>(); for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { for (int k = j + 1; k < nums.length; k++) { if (nums[i] + nums[j] + nums[k] == target) { List<Integer> temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(nums[k]); Collections.sort(temp); arr.add(temp); } } } } arr = new ArrayList<List<Integer>>(new LinkedHashSet<List<Integer>>(arr)); return arr; } public List<List<Integer>> twoPointer(int[] nums, int target) { Arrays.sort(nums); List<List<Integer>> arr = new ArrayList<List<Integer>>(); int start = 0; int end = 0; int i = 0; while (i < nums.length - 1) { start = i + 1; end = nums.length - 1; while (start < end) { if (nums[start] + nums[end] + nums[i] == target) { List<Integer> temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[start]); temp.add(nums[end]); arr.add(temp); start++; end--; } else if (nums[start] + nums[end] + nums[i] < target) { start += 1; } else { end -= 1; } } i++; } Set<List<Integer>> set = new LinkedHashSet<List<Integer>>(arr); return new ArrayList<List<Integer>>(set); } public List<List<Integer>> hashMap(int[] nums, int target) { Arrays.sort(nums); Set<List<Integer>> ts = new HashSet<>(); HashMap<Integer, Integer> hm = new HashMap<>(); for (int i = 0; i < nums.length; i++) { hm.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { int t = target - nums[i] - nums[j]; if (hm.containsKey(t) && hm.get(t) > j) { List<Integer> temp = new ArrayList<>(); temp.add(nums[i]); temp.add(nums[j]); temp.add(t); ts.add(temp); } } } return new ArrayList<>(ts); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
src/main/java/com/thealgorithms/misc/RangeInSortedArray.java
package com.thealgorithms.misc; /** * Utility class for operations to find the range of occurrences of a key * in a sorted (non-decreasing) array, and to count elements less than or equal to a given key. */ public final class RangeInSortedArray { private RangeInSortedArray() { } /** * Finds the first and last occurrence indices of the key in a sorted array. * * @param nums sorted array of integers (non-decreasing order) * @param key the target value to search for * @return int array of size two where * - index 0 is the first occurrence of key, * - index 1 is the last occurrence of key, * or [-1, -1] if the key does not exist in the array. */ public static int[] sortedRange(int[] nums, int key) { int[] range = new int[] {-1, -1}; alteredBinSearchIter(nums, key, 0, nums.length - 1, range, true); // find left boundary alteredBinSearchIter(nums, key, 0, nums.length - 1, range, false); // find right boundary return range; } /** * Recursive altered binary search to find either the leftmost or rightmost occurrence of a key. * * @param nums the sorted array * @param key the target to find * @param left current left bound in search * @param right current right bound in search * @param range array to update with boundaries: range[0] for leftmost, range[1] for rightmost * @param goLeft if true, searches for leftmost occurrence; if false, for rightmost occurrence */ public static void alteredBinSearch(int[] nums, int key, int left, int right, int[] range, boolean goLeft) { if (left > right) { return; } int mid = left + ((right - left) >>> 1); if (nums[mid] > key) { alteredBinSearch(nums, key, left, mid - 1, range, goLeft); } else if (nums[mid] < key) { alteredBinSearch(nums, key, mid + 1, right, range, goLeft); } else { if (goLeft) { if (mid == 0 || nums[mid - 1] != key) { range[0] = mid; } else { alteredBinSearch(nums, key, left, mid - 1, range, goLeft); } } else { if (mid == nums.length - 1 || nums[mid + 1] != key) { range[1] = mid; } else { alteredBinSearch(nums, key, mid + 1, right, range, goLeft); } } } } /** * Iterative altered binary search to find either the leftmost or rightmost occurrence of a key. * * @param nums the sorted array * @param key the target to find * @param left initial left bound * @param right initial right bound * @param range array to update with boundaries: range[0] for leftmost, range[1] for rightmost * @param goLeft if true, searches for leftmost occurrence; if false, for rightmost occurrence */ public static void alteredBinSearchIter(int[] nums, int key, int left, int right, int[] range, boolean goLeft) { while (left <= right) { int mid = left + ((right - left) >>> 1); if (nums[mid] > key) { right = mid - 1; } else if (nums[mid] < key) { left = mid + 1; } else { if (goLeft) { if (mid == 0 || nums[mid - 1] != key) { range[0] = mid; return; } right = mid - 1; } else { if (mid == nums.length - 1 || nums[mid + 1] != key) { range[1] = mid; return; } left = mid + 1; } } } } /** * Counts the number of elements strictly less than the given key. * * @param nums sorted array * @param key the key to compare * @return the count of elements less than the key */ public static int getCountLessThan(int[] nums, int key) { return getLessThan(nums, key, 0, nums.length - 1); } /** * Helper method using binary search to count elements less than or equal to the key. * * @param nums sorted array * @param key the key to compare * @param left current left bound * @param right current right bound * @return count of elements less than or equal to the key */ public static int getLessThan(int[] nums, int key, int left, int right) { int count = 0; while (left <= right) { int mid = left + ((right - left) >>> 1); if (nums[mid] > key) { right = mid - 1; } else { // nums[mid] <= key count = mid + 1; // all elements from 0 to mid inclusive are <= key left = mid + 1; } } return count; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayByte.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArrayByte.java
package com.thealgorithms.misc; public final class MedianOfRunningArrayByte extends MedianOfRunningArray<Byte> { @Override public Byte calculateAverage(final Byte a, final Byte b) { return (byte) ((a + b) / 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/misc/MapReduce.java
src/main/java/com/thealgorithms/misc/MapReduce.java
package com.thealgorithms.misc; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; /** * MapReduce is a programming model for processing and generating large data sets * using a parallel, distributed algorithm on a cluster. * It consists of two main phases: * - Map: the input data is split into smaller chunks and processed in parallel. * - Reduce: the results from the Map phase are aggregated to produce the final output. * * See also: https://en.wikipedia.org/wiki/MapReduce */ public final class MapReduce { private MapReduce() { } /** * Counts the frequency of each word in a given sentence using a simple MapReduce-style approach. * * @param sentence the input sentence * @return a string representing word frequencies in the format "word: count,word: count,..." */ public static String countWordFrequencies(String sentence) { // Map phase: split the sentence into words List<String> words = Arrays.asList(sentence.trim().split("\\s+")); // Group and count occurrences of each word, maintain insertion order Map<String, Long> wordCounts = words.stream().collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting())); // Reduce phase: format the result return wordCounts.entrySet().stream().map(entry -> entry.getKey() + ": " + entry.getValue()).collect(Collectors.joining(",")); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArray.java
package com.thealgorithms.misc; import java.util.Collections; import java.util.PriorityQueue; /** * A generic abstract class to compute the median of a dynamically growing stream of numbers. * * @param <T> the number type, must extend Number and be Comparable * * Usage: * Extend this class and implement {@code calculateAverage(T a, T b)} to define how averaging is done. */ public abstract class MedianOfRunningArray<T extends Number & Comparable<T>> { private final PriorityQueue<T> maxHeap; // Lower half (max-heap) private final PriorityQueue<T> minHeap; // Upper half (min-heap) public MedianOfRunningArray() { this.maxHeap = new PriorityQueue<>(Collections.reverseOrder()); this.minHeap = new PriorityQueue<>(); } /** * Inserts a new number into the data structure. * * @param element the number to insert */ public final void insert(final T element) { if (!minHeap.isEmpty() && element.compareTo(minHeap.peek()) < 0) { maxHeap.offer(element); balanceHeapsIfNeeded(); } else { minHeap.offer(element); balanceHeapsIfNeeded(); } } /** * Returns the median of the current elements. * * @return the median value * @throws IllegalArgumentException if no elements have been inserted */ public final T getMedian() { if (maxHeap.isEmpty() && minHeap.isEmpty()) { throw new IllegalArgumentException("Median is undefined for an empty data set."); } if (maxHeap.size() == minHeap.size()) { return calculateAverage(maxHeap.peek(), minHeap.peek()); } return (maxHeap.size() > minHeap.size()) ? maxHeap.peek() : minHeap.peek(); } /** * Calculates the average between two values. * Concrete subclasses must define how averaging works (e.g., for Integer, Double, etc.). * * @param a first number * @param b second number * @return the average of a and b */ protected abstract T calculateAverage(T a, T b); /** * Balances the two heaps so that their sizes differ by at most 1. */ private void balanceHeapsIfNeeded() { if (maxHeap.size() > minHeap.size() + 1) { minHeap.offer(maxHeap.poll()); } else if (minHeap.size() > maxHeap.size() + 1) { maxHeap.offer(minHeap.poll()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/PalindromePrime.java
src/main/java/com/thealgorithms/misc/PalindromePrime.java
package com.thealgorithms.misc; import java.util.ArrayList; import java.util.List; public final class PalindromePrime { private PalindromePrime() { } public static boolean prime(int num) { if (num < 2) { return false; // Handle edge case for numbers < 2 } if (num == 2) { return true; // 2 is prime } if (num % 2 == 0) { return false; // Even numbers > 2 are not prime } for (int divisor = 3; divisor <= Math.sqrt(num); divisor += 2) { if (num % divisor == 0) { return false; } } return true; } public static int reverse(int n) { int reverse = 0; while (n != 0) { reverse = reverse * 10 + (n % 10); n /= 10; } return reverse; } public static List<Integer> generatePalindromePrimes(int n) { List<Integer> palindromicPrimes = new ArrayList<>(); if (n <= 0) { return palindromicPrimes; // Handle case for 0 or negative input } palindromicPrimes.add(2); // 2 is the first palindromic prime int count = 1; int num = 3; while (count < n) { if (num == reverse(num) && prime(num)) { palindromicPrimes.add(num); count++; } num += 2; // Skip even numbers } return palindromicPrimes; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/ShuffleArray.java
src/main/java/com/thealgorithms/misc/ShuffleArray.java
package com.thealgorithms.misc; import java.util.Random; /** * The Fisher-Yates (Knuth) Shuffle algorithm randomly permutes an array's * elements, ensuring each permutation is equally likely. * * <p> * Worst-case performance O(n) * Best-case performance O(n) * Average performance O(n) * Worst-case space complexity O(1) * * This class provides a static method to shuffle an array in place. * * @author Rashi Dashore (https://github.com/rashi07dashore) */ public final class ShuffleArray { private ShuffleArray() { } /** * Shuffles the provided array in-place using the Fisher–Yates algorithm. * * @param arr the array to shuffle; must not be {@code null} * @throws IllegalArgumentException if the input array is {@code null} */ public static void shuffle(int[] arr) { if (arr == null) { throw new IllegalArgumentException("Input array must not be null"); } Random random = new Random(); for (int i = arr.length - 1; i > 0; i--) { int j = random.nextInt(i + 1); swap(arr, i, j); } } /** * Swaps two elements in an array. * * @param arr the array * @param i index of first element * @param j index of second element */ private static void swap(int[] arr, int i, int j) { if (i != j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/TwoSumProblem.java
src/main/java/com/thealgorithms/misc/TwoSumProblem.java
package com.thealgorithms.misc; import java.util.HashMap; import java.util.Optional; import org.apache.commons.lang3.tuple.Pair; public final class TwoSumProblem { private TwoSumProblem() { } /** * The function "twoSum" takes an array of integers and a target integer as input, and returns an * array of two indices where the corresponding elements in the input array add up to the target. * @param values An array of integers. * @param target The target is the sum that we are trying to find using two numbers from the given array. * @return A pair or indexes such that sum of values at these indexes equals to the target * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) */ public static Optional<Pair<Integer, Integer>> twoSum(final int[] values, final int target) { HashMap<Integer, Integer> valueToIndex = new HashMap<>(); for (int i = 0; i < values.length; i++) { final var remainder = target - values[i]; if (valueToIndex.containsKey(remainder)) { return Optional.of(Pair.of(valueToIndex.get(remainder), i)); } if (!valueToIndex.containsKey(values[i])) { valueToIndex.put(values[i], i); } } return Optional.empty(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayFloat.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArrayFloat.java
package com.thealgorithms.misc; public final class MedianOfRunningArrayFloat extends MedianOfRunningArray<Float> { @Override public Float calculateAverage(final Float a, final Float b) { return (a + b) / 2.0f; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayDouble.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArrayDouble.java
package com.thealgorithms.misc; public final class MedianOfRunningArrayDouble extends MedianOfRunningArray<Double> { @Override public Double calculateAverage(final Double a, final Double b) { return (a + b) / 2.0d; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/Sparsity.java
src/main/java/com/thealgorithms/misc/Sparsity.java
package com.thealgorithms.misc; /** * Utility class for calculating the sparsity of a matrix. * A matrix is considered sparse if a large proportion of its elements are zero. * Typically, if more than 2/3 of the elements are zero, the matrix is considered sparse. * * Sparsity is defined as: * sparsity = (number of zero elements) / (total number of elements) * * This can lead to significant computational optimizations. */ public final class Sparsity { private Sparsity() { } /** * Calculates the sparsity of a given 2D matrix. * * @param matrix the input matrix * @return the sparsity value between 0 and 1 * @throws IllegalArgumentException if the matrix is null, empty, or contains empty rows */ public static double sparsity(double[][] matrix) { if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { throw new IllegalArgumentException("Matrix cannot be null or empty"); } int zeroCount = 0; int totalElements = 0; // Count the number of zero elements and total elements for (double[] row : matrix) { for (double value : row) { if (value == 0.0) { zeroCount++; } totalElements++; } } // Return sparsity as a double return (double) zeroCount / totalElements; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/misc/ColorContrastRatio.java
src/main/java/com/thealgorithms/misc/ColorContrastRatio.java
package com.thealgorithms.misc; import java.awt.Color; /** * @brief A Java implementation of the official W3 documented procedure to * calculate contrast ratio between colors on the web. This is used to calculate * the readability of a foreground color on top of a background color. * @since 2020-10-15 * @see <a href="https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-procedure">Color Contrast Ratio</a> * @author [Seth Falco](https://github.com/SethFalco) */ public class ColorContrastRatio { /** * @brief Calculates the contrast ratio between two given colors. * @param a Any color, used to get the red, green, and blue values. * @param b Another color, which will be compared against the first color. * @return The contrast ratio between the two colors. */ public double getContrastRatio(Color a, Color b) { final double aColorLuminance = getRelativeLuminance(a); final double bColorLuminance = getRelativeLuminance(b); if (aColorLuminance > bColorLuminance) { return (aColorLuminance + 0.05) / (bColorLuminance + 0.05); } return (bColorLuminance + 0.05) / (aColorLuminance + 0.05); } /** * @brief Calculates the relative luminance of a given color. * @param color Any color, used to get the red, green, and blue values. * @return The relative luminance of the color. * @see <a href="https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef">More info on relative luminance.</a> */ public double getRelativeLuminance(Color color) { final double red = getColor(color.getRed()); final double green = getColor(color.getGreen()); final double blue = getColor(color.getBlue()); return 0.2126 * red + 0.7152 * green + 0.0722 * blue; } /** * @brief Calculates the final value for a color to be used in the relative luminance formula as described in step 1. * @param color8Bit 8-bit representation of a color component value. * @return Value for the provided color component to be used in the relative luminance formula. */ public double getColor(int color8Bit) { final double sRgb = getColorSRgb(color8Bit); return (sRgb <= 0.03928) ? sRgb / 12.92 : Math.pow((sRgb + 0.055) / 1.055, 2.4); } /** * @brief Calculates the Color sRGB value as denoted in step 1 of the procedure document. * @param color8Bit 8-bit representation of a color component value. * @return A percentile value of the color component. */ private double getColorSRgb(double color8Bit) { return color8Bit / 255.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/misc/MedianOfRunningArrayLong.java
src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java
package com.thealgorithms.misc; public final class MedianOfRunningArrayLong extends MedianOfRunningArray<Long> { @Override public Long calculateAverage(final Long a, final Long b) { return (a + b) / 2L; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/PreemptivePriorityScheduling.java
src/main/java/com/thealgorithms/scheduling/PreemptivePriorityScheduling.java
package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; /** * Preemptive Priority Scheduling Algorithm * * @author [Bama Charan Chhandogi](https://www.github.com/BamaCharanChhandogi) */ public class PreemptivePriorityScheduling { protected final List<ProcessDetails> processes; protected final List<String> ganttChart; public PreemptivePriorityScheduling(Collection<ProcessDetails> processes) { this.processes = new ArrayList<>(processes); this.ganttChart = new ArrayList<>(); } public void scheduleProcesses() { PriorityQueue<ProcessDetails> readyQueue = new PriorityQueue<>(Comparator.comparingInt(ProcessDetails::getPriority).reversed().thenComparingInt(ProcessDetails::getArrivalTime)); int currentTime = 0; List<ProcessDetails> arrivedProcesses = new ArrayList<>(); while (!processes.isEmpty() || !readyQueue.isEmpty()) { updateArrivedProcesses(currentTime, arrivedProcesses); readyQueue.addAll(arrivedProcesses); arrivedProcesses.clear(); if (!readyQueue.isEmpty()) { ProcessDetails currentProcess = readyQueue.poll(); ganttChart.add(currentProcess.getProcessId()); currentProcess.setBurstTime(currentProcess.getBurstTime() - 1); if (currentProcess.getBurstTime() > 0) { readyQueue.add(currentProcess); } } else { ganttChart.add("Idle"); } currentTime++; } } private void updateArrivedProcesses(int currentTime, List<ProcessDetails> arrivedProcesses) { processes.removeIf(process -> { if (process.getArrivalTime() <= currentTime) { arrivedProcesses.add(process); 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/scheduling/LotteryScheduling.java
src/main/java/com/thealgorithms/scheduling/LotteryScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * The LotteryScheduling class implements the Lottery Scheduling algorithm, which is * a probabilistic CPU scheduling algorithm. Processes are assigned tickets, and * the CPU is allocated to a randomly selected process based on ticket count. * Processes with more tickets have a higher chance of being selected. */ public final class LotteryScheduling { private LotteryScheduling() { } private List<Process> processes; private Random random; /** * Constructs a LotteryScheduling object with the provided list of processes. * * @param processes List of processes to be scheduled using Lottery Scheduling. */ public LotteryScheduling(final List<Process> processes) { this.processes = processes; this.random = new Random(); } /** * Constructs a LotteryScheduling object with the provided list of processes and a Random object. * * @param processes List of processes to be scheduled using Lottery Scheduling. * @param random Random object used for generating random numbers. */ public LotteryScheduling(final List<Process> processes, Random random) { this.processes = processes; this.random = random; } /** * Schedules the processes using the Lottery Scheduling algorithm. * Each process is assigned a certain number of tickets, and the algorithm randomly * selects a process to execute based on ticket count. The method calculates the * waiting time and turnaround time for each process and simulates their execution. */ public List<Process> scheduleProcesses() { int totalTickets = processes.stream().mapToInt(Process::getTickets).sum(); int currentTime = 0; List<Process> executedProcesses = new ArrayList<>(); while (!processes.isEmpty()) { int winningTicket = random.nextInt(totalTickets) + 1; Process selectedProcess = selectProcessByTicket(winningTicket); if (selectedProcess == null) { // This should not happen in normal circumstances, but we'll handle it just in case System.err.println("Error: No process selected. Recalculating total tickets."); totalTickets = processes.stream().mapToInt(Process::getTickets).sum(); continue; } selectedProcess.setWaitingTime(currentTime); currentTime += selectedProcess.getBurstTime(); selectedProcess.setTurnAroundTime(selectedProcess.getWaitingTime() + selectedProcess.getBurstTime()); executedProcesses.add(selectedProcess); processes.remove(selectedProcess); totalTickets = processes.stream().mapToInt(Process::getTickets).sum(); } return executedProcesses; } /** * Selects a process based on a winning ticket. The method iterates over the * list of processes, and as the ticket sum accumulates, it checks if the * current process holds the winning ticket. * * @param winningTicket The randomly generated ticket number that determines the selected process. * @return The process associated with the winning ticket. */ private Process selectProcessByTicket(int winningTicket) { int ticketSum = 0; for (Process process : processes) { ticketSum += process.getTickets(); if (ticketSum >= winningTicket) { return process; } } return null; } /** * The Process class represents a process in the scheduling system. Each process has * an ID, burst time (CPU time required for execution), number of tickets (used in * lottery selection), waiting time, and turnaround time. */ public static class Process { private String processId; private int burstTime; private int tickets; private int waitingTime; private int turnAroundTime; public Process(String processId, int burstTime, int tickets) { this.processId = processId; this.burstTime = burstTime; this.tickets = tickets; } public String getProcessId() { return processId; } public int getBurstTime() { return burstTime; } public int getTickets() { return tickets; } public int getWaitingTime() { return waitingTime; } public void setWaitingTime(int waitingTime) { this.waitingTime = waitingTime; } public int getTurnAroundTime() { return turnAroundTime; } public void setTurnAroundTime(int turnAroundTime) { this.turnAroundTime = turnAroundTime; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java
src/main/java/com/thealgorithms/scheduling/ProportionalFairScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.List; /** * ProportionalFairScheduling allocates resources to processes based on their * proportional weight or importance. It aims to balance fairness with * priority, ensuring that higher-weight processes receive a larger share of resources. * * Use Case: Network bandwidth allocation in cellular networks (4G/5G), * where devices receive a proportional share of bandwidth. * * @author Hardvan */ public final class ProportionalFairScheduling { static class Process { String name; int weight; int allocatedResources; Process(String name, int weight) { this.name = name; this.weight = weight; this.allocatedResources = 0; } } private final List<Process> processes; public ProportionalFairScheduling() { processes = new ArrayList<>(); } public void addProcess(String name, int weight) { processes.add(new Process(name, weight)); } public void allocateResources(int totalResources) { int totalWeight = processes.stream().mapToInt(p -> p.weight).sum(); for (Process process : processes) { process.allocatedResources = (int) ((double) process.weight / totalWeight * totalResources); } } public List<String> getAllocatedResources() { List<String> allocation = new ArrayList<>(); for (Process process : processes) { allocation.add(process.name + ": " + process.allocatedResources); } return allocation; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java
src/main/java/com/thealgorithms/scheduling/SelfAdjustingScheduling.java
package com.thealgorithms.scheduling; import java.util.PriorityQueue; /** * SelfAdjustingScheduling is an algorithm where tasks dynamically adjust * their priority based on real-time feedback, such as wait time and CPU usage. * Tasks that wait longer will automatically increase their priority, * allowing for better responsiveness and fairness in task handling. * * Use Case: Real-time systems that require dynamic prioritization * of tasks to maintain system responsiveness and fairness. * * @author Hardvan */ public final class SelfAdjustingScheduling { private static class Task implements Comparable<Task> { String name; int waitTime; int priority; Task(String name, int priority) { this.name = name; this.waitTime = 0; this.priority = priority; } void incrementWaitTime() { waitTime++; priority = priority + waitTime; } @Override public int compareTo(Task other) { return Integer.compare(this.priority, other.priority); } } private final PriorityQueue<Task> taskQueue; public SelfAdjustingScheduling() { taskQueue = new PriorityQueue<>(); } public void addTask(String name, int priority) { taskQueue.offer(new Task(name, priority)); } public String scheduleNext() { if (taskQueue.isEmpty()) { return null; } Task nextTask = taskQueue.poll(); nextTask.incrementWaitTime(); taskQueue.offer(nextTask); return nextTask.name; } public boolean isEmpty() { return taskQueue.isEmpty(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java
src/main/java/com/thealgorithms/scheduling/HighestResponseRatioNextScheduling.java
package com.thealgorithms.scheduling; import java.util.Arrays; import java.util.Comparator; /** * The {@code HighestResponseRatioNextScheduling} class implements the * Highest Response Ratio Next (HRRN) scheduling algorithm. * HRRN is a non-preemptive scheduling algorithm that selects the process with * the highest response ratio for execution. * The response ratio is calculated as: * * <pre> * Response Ratio = (waiting time + burst time) / burst time * </pre> * * HRRN is designed to reduce the average waiting time and improve overall * system performance by balancing between short and long processes, * minimizing process starvation. */ public final class HighestResponseRatioNextScheduling { private static final int PROCESS_NOT_FOUND = -1; private static final double INITIAL_MAX_RESPONSE_RATIO = -1.0; private HighestResponseRatioNextScheduling() { } /** * Represents a process in the scheduling algorithm. */ private static class Process { String name; int arrivalTime; int burstTime; int turnAroundTime; boolean finished; Process(String name, int arrivalTime, int burstTime) { this.name = name; this.arrivalTime = arrivalTime; this.burstTime = burstTime; this.turnAroundTime = 0; this.finished = false; } /** * Calculates the response ratio for this process. * * @param currentTime The current time in the scheduling process. * @return The response ratio for this process. */ double calculateResponseRatio(int currentTime) { return (double) (burstTime + currentTime - arrivalTime) / burstTime; } } /** * Calculates the Turn Around Time (TAT) for each process. * * <p>Turn Around Time is calculated as the total time a process spends * in the system from arrival to completion. It is the sum of the burst time * and the waiting time.</p> * * @param processNames Array of process names. * @param arrivalTimes Array of arrival times corresponding to each process. * @param burstTimes Array of burst times for each process. * @param noOfProcesses The number of processes. * @return An array of Turn Around Times for each process. */ public static int[] calculateTurnAroundTime(final String[] processNames, final int[] arrivalTimes, final int[] burstTimes, final int noOfProcesses) { int currentTime = 0; int[] turnAroundTime = new int[noOfProcesses]; Process[] processes = new Process[noOfProcesses]; for (int i = 0; i < noOfProcesses; i++) { processes[i] = new Process(processNames[i], arrivalTimes[i], burstTimes[i]); } Arrays.sort(processes, Comparator.comparingInt(p -> p.arrivalTime)); int finishedProcessCount = 0; while (finishedProcessCount < noOfProcesses) { int nextProcessIndex = findNextProcess(processes, currentTime); if (nextProcessIndex == PROCESS_NOT_FOUND) { currentTime++; continue; } Process currentProcess = processes[nextProcessIndex]; currentTime = Math.max(currentTime, currentProcess.arrivalTime); currentProcess.turnAroundTime = currentTime + currentProcess.burstTime - currentProcess.arrivalTime; currentTime += currentProcess.burstTime; currentProcess.finished = true; finishedProcessCount++; } for (int i = 0; i < noOfProcesses; i++) { turnAroundTime[i] = processes[i].turnAroundTime; } return turnAroundTime; } /** * Calculates the Waiting Time (WT) for each process. * * @param turnAroundTime The Turn Around Times for each process. * @param burstTimes The burst times for each process. * @return An array of Waiting Times for each process. */ public static int[] calculateWaitingTime(int[] turnAroundTime, int[] burstTimes) { int[] waitingTime = new int[turnAroundTime.length]; for (int i = 0; i < turnAroundTime.length; i++) { waitingTime[i] = turnAroundTime[i] - burstTimes[i]; } return waitingTime; } /** * Finds the next process to be scheduled based on arrival times and the current time. * * @param processes Array of Process objects. * @param currentTime The current time in the scheduling process. * @return The index of the next process to be scheduled, or PROCESS_NOT_FOUND if no process is ready. */ private static int findNextProcess(Process[] processes, int currentTime) { return findHighestResponseRatio(processes, currentTime); } /** * Finds the process with the highest response ratio. * * <p>The response ratio is calculated as: * (waiting time + burst time) / burst time * where waiting time = current time - arrival time</p> * * @param processes Array of Process objects. * @param currentTime The current time in the scheduling process. * @return The index of the process with the highest response ratio, or PROCESS_NOT_FOUND if no process is ready. */ private static int findHighestResponseRatio(Process[] processes, int currentTime) { double maxResponseRatio = INITIAL_MAX_RESPONSE_RATIO; int maxIndex = PROCESS_NOT_FOUND; for (int i = 0; i < processes.length; i++) { Process process = processes[i]; if (!process.finished && process.arrivalTime <= currentTime) { double responseRatio = process.calculateResponseRatio(currentTime); if (responseRatio > maxResponseRatio) { maxResponseRatio = responseRatio; maxIndex = i; } } } return maxIndex; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java
src/main/java/com/thealgorithms/scheduling/JobSchedulingWithDeadline.java
package com.thealgorithms.scheduling; import java.util.Arrays; import java.util.Comparator; /** * A class that implements a job scheduling algorithm to maximize profit * while adhering to job deadlines and arrival times. * * This class provides functionality to schedule jobs based on their profit, * arrival time, and deadlines to ensure that the maximum number of jobs is completed * within the given timeframe. It sorts the jobs in decreasing order of profit * and attempts to assign them to the latest possible time slots. */ public final class JobSchedulingWithDeadline { private JobSchedulingWithDeadline() { } /** * Represents a job with an ID, arrival time, deadline, and profit. * * Each job has a unique identifier, an arrival time (when it becomes available for scheduling), * a deadline by which it must be completed, and a profit associated with completing the job. */ static class Job { int jobId; int arrivalTime; int deadline; int profit; /** * Constructs a Job instance with the specified job ID, arrival time, deadline, and profit. * * @param jobId Unique identifier for the job * @param arrivalTime Time when the job becomes available for scheduling * @param deadline Deadline for completing the job * @param profit Profit earned upon completing the job */ Job(int jobId, int arrivalTime, int deadline, int profit) { this.jobId = jobId; this.arrivalTime = arrivalTime; this.deadline = deadline; this.profit = profit; } } /** * Schedules jobs to maximize profit while respecting their deadlines and arrival times. * * This method sorts the jobs in descending order of profit and attempts * to allocate them to time slots that are before or on their deadlines, * provided they have arrived. The function returns an array where the first element * is the total number of jobs scheduled and the second element is the total profit earned. * * @param jobs An array of Job objects, each representing a job with an ID, arrival time, * deadline, and profit. * @return An array of two integers: the first element is the count of jobs * that were successfully scheduled, and the second element is the * total profit earned from those jobs. */ public static int[] jobSequencingWithDeadlines(Job[] jobs) { Arrays.sort(jobs, Comparator.comparingInt(job -> - job.profit)); int maxDeadline = Arrays.stream(jobs).mapToInt(job -> job.deadline).max().orElse(0); int[] timeSlots = new int[maxDeadline]; Arrays.fill(timeSlots, -1); int count = 0; int maxProfit = 0; // Schedule the jobs for (Job job : jobs) { if (job.arrivalTime <= job.deadline) { for (int i = Math.min(job.deadline - 1, maxDeadline - 1); i >= job.arrivalTime - 1; i--) { if (timeSlots[i] == -1) { timeSlots[i] = job.jobId; count++; maxProfit += job.profit; break; } } } } return new int[] {count, maxProfit}; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/EDFScheduling.java
src/main/java/com/thealgorithms/scheduling/EDFScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * The Earliest Deadline First (EDF) Scheduling class implements a dynamic scheduling algorithm. * It assigns the CPU to processes with the earliest deadlines, ensuring that deadlines are met if possible. * This scheduling algorithm is ideal for real-time systems where meeting deadlines is critical. */ public final class EDFScheduling { private EDFScheduling() { } private List<Process> processes; /** * Constructs an EDFScheduling object with a list of processes. * * @param processes List of processes to be scheduled. */ public EDFScheduling(final List<Process> processes) { this.processes = processes; } /** * Schedules the processes using Earliest Deadline First (EDF) scheduling. * Processes are sorted by their deadlines, and the method simulates their execution. * It calculates the waiting time and turnaround time for each process. * * @return List of processes after they have been executed in order of earliest deadline first. */ public List<Process> scheduleProcesses() { processes.sort(Comparator.comparingInt(Process::getDeadline)); int currentTime = 0; List<Process> executedProcesses = new ArrayList<>(); for (Process process : processes) { process.setWaitingTime(currentTime); currentTime += process.getBurstTime(); process.setTurnAroundTime(process.getWaitingTime() + process.getBurstTime()); if (currentTime > process.getDeadline()) { System.out.println("Warning: Process " + process.getProcessId() + " missed its deadline."); } executedProcesses.add(process); } return executedProcesses; } /** * The Process class represents a process with an ID, burst time, deadline, waiting time, and turnaround time. */ public static class Process { private String processId; private int burstTime; private int deadline; private int waitingTime; private int turnAroundTime; public Process(String processId, int burstTime, int deadline) { this.processId = processId; this.burstTime = burstTime; this.deadline = deadline; } public String getProcessId() { return processId; } public int getBurstTime() { return burstTime; } public int getDeadline() { return deadline; } public int getWaitingTime() { return waitingTime; } public void setWaitingTime(int waitingTime) { this.waitingTime = waitingTime; } public int getTurnAroundTime() { return turnAroundTime; } public void setTurnAroundTime(int turnAroundTime) { this.turnAroundTime = turnAroundTime; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java
src/main/java/com/thealgorithms/scheduling/SlackTimeScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * SlackTimeScheduling is an algorithm that prioritizes tasks based on their * slack time, which is defined as the difference between the task's deadline * and the time required to execute it. Tasks with less slack time are prioritized. * * Use Case: Real-time systems with hard deadlines, such as robotics or embedded systems. * * @author Hardvan */ public class SlackTimeScheduling { static class Task { String name; int executionTime; int deadline; Task(String name, int executionTime, int deadline) { this.name = name; this.executionTime = executionTime; this.deadline = deadline; } int getSlackTime() { return deadline - executionTime; } } private final List<Task> tasks; public SlackTimeScheduling() { tasks = new ArrayList<>(); } /** * Adds a task to the scheduler. * * @param name the name of the task * @param executionTime the time required to execute the task * @param deadline the deadline by which the task must be completed */ public void addTask(String name, int executionTime, int deadline) { tasks.add(new Task(name, executionTime, deadline)); } /** * Schedules the tasks based on their slack time. * * @return the order in which the tasks should be executed */ public List<String> scheduleTasks() { tasks.sort(Comparator.comparingInt(Task::getSlackTime)); List<String> scheduledOrder = new ArrayList<>(); for (Task task : tasks) { scheduledOrder.add(task.name); } return scheduledOrder; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java
src/main/java/com/thealgorithms/scheduling/FairShareScheduling.java
package com.thealgorithms.scheduling; import java.util.HashMap; import java.util.Map; /** * FairShareScheduling allocates CPU resources equally among users or groups * instead of individual tasks. Each group gets a proportional share, * preventing resource hogging by a single user's processes. * * Use Case: Multi-user systems where users submit multiple tasks simultaneously, * such as cloud environments. * * @author Hardvan */ public final class FairShareScheduling { static class User { String name; int allocatedResources; int totalWeight; User(String name) { this.name = name; this.allocatedResources = 0; this.totalWeight = 0; } void addWeight(int weight) { this.totalWeight += weight; } } private final Map<String, User> users; // username -> User public FairShareScheduling() { users = new HashMap<>(); } public void addUser(String userName) { users.putIfAbsent(userName, new User(userName)); } public void addTask(String userName, int weight) { User user = users.get(userName); if (user != null) { user.addWeight(weight); } } public void allocateResources(int totalResources) { int totalWeights = users.values().stream().mapToInt(user -> user.totalWeight).sum(); for (User user : users.values()) { user.allocatedResources = (int) ((double) user.totalWeight / totalWeights * totalResources); } } public Map<String, Integer> getAllocatedResources() { Map<String, Integer> allocation = new HashMap<>(); for (User user : users.values()) { allocation.put(user.name, user.allocatedResources); } return allocation; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java
src/main/java/com/thealgorithms/scheduling/MultiAgentScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * MultiAgentScheduling assigns tasks to different autonomous agents * who independently decide the execution order of their assigned tasks. * The focus is on collaboration between agents to optimize the overall schedule. * * Use Case: Distributed scheduling in decentralized systems like IoT networks. * * @author Hardvan */ public class MultiAgentScheduling { static class Agent { String name; List<String> tasks; Agent(String name) { this.name = name; this.tasks = new ArrayList<>(); } void addTask(String task) { tasks.add(task); } List<String> getTasks() { return tasks; } } private final Map<String, Agent> agents; public MultiAgentScheduling() { agents = new HashMap<>(); } public void addAgent(String agentName) { agents.putIfAbsent(agentName, new Agent(agentName)); } /** * Assign a task to a specific agent. * * @param agentName the name of the agent * @param task the task to be assigned */ public void assignTask(String agentName, String task) { Agent agent = agents.get(agentName); if (agent != null) { agent.addTask(task); } } /** * Get the scheduled tasks for each agent. * * @return a map of agent names to their scheduled tasks */ public Map<String, List<String>> getScheduledTasks() { Map<String, List<String>> schedule = new HashMap<>(); for (Agent agent : agents.values()) { schedule.put(agent.name, agent.getTasks()); } return schedule; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java
src/main/java/com/thealgorithms/scheduling/MLFQScheduler.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * The Multi-Level Feedback Queue (MLFQ) Scheduler class. * This class simulates scheduling using multiple queues, where processes move * between queues depending on their CPU burst behavior. */ public class MLFQScheduler { private List<Queue<Process>> queues; // Multi-level feedback queues private int[] timeQuantum; // Time quantum for each queue level private int currentTime; // Current time in the system /** * Constructor to initialize the MLFQ scheduler with the specified number of * levels and their corresponding time quantums. * * @param levels Number of queues (priority levels) * @param timeQuantums Time quantum for each queue level */ public MLFQScheduler(int levels, int[] timeQuantums) { queues = new ArrayList<>(levels); for (int i = 0; i < levels; i++) { queues.add(new LinkedList<>()); } timeQuantum = timeQuantums; currentTime = 0; } /** * Adds a new process to the highest priority queue (queue 0). * * @param p The process to be added to the scheduler */ public void addProcess(Process p) { queues.get(0).add(p); } /** * Executes the scheduling process by running the processes in all queues, * promoting or demoting them based on their completion status and behavior. * The process continues until all queues are empty. */ public void run() { while (!allQueuesEmpty()) { for (int i = 0; i < queues.size(); i++) { Queue<Process> queue = queues.get(i); if (!queue.isEmpty()) { Process p = queue.poll(); int quantum = timeQuantum[i]; // Execute the process for the minimum of the time quantum or the remaining time int timeSlice = Math.min(quantum, p.remainingTime); p.execute(timeSlice); currentTime += timeSlice; // Update the system's current time if (p.isFinished()) { System.out.println("Process " + p.pid + " finished at time " + currentTime); } else { if (i < queues.size() - 1) { p.priority++; // Demote the process to the next lower priority queue queues.get(i + 1).add(p); // Add to the next queue level } else { queue.add(p); // Stay in the same queue if it's the last level } } } } } } /** * Helper function to check if all the queues are empty (i.e., no process is * left to execute). * * @return true if all queues are empty, otherwise false */ private boolean allQueuesEmpty() { for (Queue<Process> queue : queues) { if (!queue.isEmpty()) { return false; } } return true; } /** * Retrieves the current time of the scheduler, which reflects the total time * elapsed during the execution of all processes. * * @return The current time in the system */ public int getCurrentTime() { return currentTime; } } /** * Represents a process in the Multi-Level Feedback Queue (MLFQ) scheduling * algorithm. */ class Process { int pid; int burstTime; int remainingTime; int arrivalTime; int priority; /** * Constructor to initialize a new process. * * @param pid Process ID * @param burstTime CPU Burst Time (time required for the process) * @param arrivalTime Arrival time of the process */ Process(int pid, int burstTime, int arrivalTime) { this.pid = pid; this.burstTime = burstTime; this.remainingTime = burstTime; this.arrivalTime = arrivalTime; this.priority = 0; } /** * Executes the process for a given time slice. * * @param timeSlice The amount of time the process is executed */ public void execute(int timeSlice) { remainingTime -= timeSlice; if (remainingTime < 0) { remainingTime = 0; } } /** * Checks if the process has finished execution. * * @return true if the process is finished, otherwise false */ public boolean isFinished() { return remainingTime == 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/scheduling/RandomScheduling.java
src/main/java/com/thealgorithms/scheduling/RandomScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Random; /** * RandomScheduling is an algorithm that assigns tasks in a random order. * It doesn't consider priority, deadlines, or burst times, making it * inefficient but useful in scenarios where fairness or unpredictability * is required (e.g., load balancing in distributed systems). * * Use Case: Distributed systems where randomness helps avoid task starvation. * * @author Hardvan */ public final class RandomScheduling { private final List<String> tasks; private final Random random; /** * Constructs a new RandomScheduling instance. * * @param tasks A collection of task names to be scheduled. * @param random A Random instance for generating random numbers. */ public RandomScheduling(Collection<String> tasks, Random random) { this.tasks = new ArrayList<>(tasks); this.random = random; } /** * Schedules the tasks randomly and returns the randomized order. * * @return A list representing the tasks in their randomized execution order. */ public List<String> schedule() { List<String> shuffledTasks = new ArrayList<>(tasks); Collections.shuffle(shuffledTasks, random); return shuffledTasks; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java
src/main/java/com/thealgorithms/scheduling/FCFSScheduling.java
package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.List; /** * Non-pre-emptive First Come First Serve scheduling. This can be understood here - * https://www.scaler.com/topics/first-come-first-serve/ */ public class FCFSScheduling { private List<ProcessDetails> processes; FCFSScheduling(final List<ProcessDetails> processes) { this.processes = processes; } public void scheduleProcesses() { evaluateWaitingTime(); evaluateTurnAroundTime(); } private void evaluateWaitingTime() { int processesNumber = processes.size(); if (processesNumber == 0) { return; } int waitingTime = 0; int burstTime = processes.get(0).getBurstTime(); processes.get(0).setWaitingTime(waitingTime); // for the first process, waiting time will be 0. for (int i = 1; i < processesNumber; i++) { processes.get(i).setWaitingTime(waitingTime + burstTime); waitingTime = processes.get(i).getWaitingTime(); burstTime = processes.get(i).getBurstTime(); } } private void evaluateTurnAroundTime() { for (final var process : processes) { process.setTurnAroundTimeTime(process.getBurstTime() + process.getWaitingTime()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java
src/main/java/com/thealgorithms/scheduling/NonPreemptivePriorityScheduling.java
package com.thealgorithms.scheduling; import java.util.Collections; import java.util.LinkedList; import java.util.PriorityQueue; import java.util.Queue; /** * This class implements the Non-Preemptive Priority Scheduling algorithm. * Processes are executed in order of their priority. The process with the * highest priority (lower priority number) is executed first, * and once a process starts executing, it cannot be preempted. */ public final class NonPreemptivePriorityScheduling { private NonPreemptivePriorityScheduling() { } /** * Represents a process with an ID, burst time, priority, arrival time, and start time. */ static class Process implements Comparable<Process> { int id; int arrivalTime; int startTime; int burstTime; int priority; /** * Constructs a Process instance with the specified parameters. * * @param id Unique identifier for the process * @param arrivalTime Time when the process arrives in the system * @param burstTime Time required for the process execution * @param priority Priority of the process */ Process(int id, int arrivalTime, int burstTime, int priority) { this.id = id; this.arrivalTime = arrivalTime; this.startTime = -1; this.burstTime = burstTime; this.priority = priority; } /** * Compare based on priority for scheduling. The process with the lowest * priority is selected first. * If two processes have the same priority, the one that arrives earlier is selected. * * @param other The other process to compare against * @return A negative integer, zero, or a positive integer as this process * is less than, equal to, or greater than the specified process. */ @Override public int compareTo(Process other) { if (this.priority == other.priority) { return Integer.compare(this.arrivalTime, other.arrivalTime); } return Integer.compare(this.priority, other.priority); } } /** * Schedules processes based on their priority in a non-preemptive manner, considering their arrival times. * * @param processes Array of processes to be scheduled. * @return Array of processes in the order they are executed. */ public static Process[] scheduleProcesses(Process[] processes) { PriorityQueue<Process> pq = new PriorityQueue<>(); Queue<Process> waitingQueue = new LinkedList<>(); int currentTime = 0; int index = 0; Process[] executionOrder = new Process[processes.length]; Collections.addAll(waitingQueue, processes); while (!waitingQueue.isEmpty() || !pq.isEmpty()) { // Add processes that have arrived to the priority queue while (!waitingQueue.isEmpty() && waitingQueue.peek().arrivalTime <= currentTime) { pq.add(waitingQueue.poll()); } if (!pq.isEmpty()) { Process currentProcess = pq.poll(); currentProcess.startTime = currentTime; executionOrder[index++] = currentProcess; currentTime += currentProcess.burstTime; } else { // If no process is ready, move to the next arrival time currentTime = waitingQueue.peek().arrivalTime; } } return executionOrder; } /** * Calculates the average waiting time of the processes. * * @param processes Array of processes. * @param executionOrder Array of processes in execution order. * @return Average waiting time. */ public static double calculateAverageWaitingTime(Process[] processes, Process[] executionOrder) { int totalWaitingTime = 0; for (Process process : executionOrder) { int waitingTime = process.startTime - process.arrivalTime; totalWaitingTime += waitingTime; } return (double) totalWaitingTime / processes.length; } /** * Calculates the average turn-around time of the processes. * * @param processes Array of processes. * @param executionOrder Array of processes in execution order. * @return Average turn-around time. */ public static double calculateAverageTurnaroundTime(Process[] processes, Process[] executionOrder) { int totalTurnaroundTime = 0; for (Process process : executionOrder) { int turnaroundTime = process.startTime + process.burstTime - process.arrivalTime; totalTurnaroundTime += turnaroundTime; } return (double) totalTurnaroundTime / processes.length; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/GangScheduling.java
src/main/java/com/thealgorithms/scheduling/GangScheduling.java
package com.thealgorithms.scheduling; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * GangScheduling groups related tasks (gangs) to run simultaneously on multiple processors. * All tasks in a gang are executed together or not at all. * * Use Case: Parallel computing environments where multiple threads of a program * need to run concurrently for optimal performance. * * @author Hardvan */ public final class GangScheduling { static class Gang { String name; List<String> tasks; Gang(String name) { this.name = name; this.tasks = new ArrayList<>(); } void addTask(String task) { tasks.add(task); } List<String> getTasks() { return tasks; } } private final Map<String, Gang> gangs; public GangScheduling() { gangs = new HashMap<>(); } public void addGang(String gangName) { gangs.putIfAbsent(gangName, new Gang(gangName)); } public void addTaskToGang(String gangName, String task) { Gang gang = gangs.get(gangName); if (gang != null) { gang.addTask(task); } } public Map<String, List<String>> getGangSchedules() { Map<String, List<String>> schedules = new HashMap<>(); for (Gang gang : gangs.values()) { schedules.put(gang.name, gang.getTasks()); } return schedules; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/SJFScheduling.java
src/main/java/com/thealgorithms/scheduling/SJFScheduling.java
package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** * Shortest Job First (SJF) Scheduling Algorithm: * Executes processes with the shortest burst time first among the ones that have arrived. */ public class SJFScheduling { private final List<ProcessDetails> processes; private final List<String> schedule; public SJFScheduling(final List<ProcessDetails> processes) { this.processes = new ArrayList<>(processes); this.schedule = new ArrayList<>(); sortProcessesByArrivalTime(this.processes); } private static void sortProcessesByArrivalTime(List<ProcessDetails> processes) { processes.sort(Comparator.comparingInt(ProcessDetails::getArrivalTime)); } /** * Executes the SJF scheduling algorithm and builds the execution order. */ public void scheduleProcesses() { List<ProcessDetails> ready = new ArrayList<>(); int size = processes.size(); int time = 0; int executed = 0; Iterator<ProcessDetails> processIterator = processes.iterator(); // This will track the next process to be checked for arrival time ProcessDetails nextProcess = null; if (processIterator.hasNext()) { nextProcess = processIterator.next(); } while (executed < size) { // Load all processes that have arrived by current time while (nextProcess != null && nextProcess.getArrivalTime() <= time) { ready.add(nextProcess); if (processIterator.hasNext()) { nextProcess = processIterator.next(); } else { nextProcess = null; } } ProcessDetails running = findShortestJob(ready); if (running == null) { time++; } else { time += running.getBurstTime(); schedule.add(running.getProcessId()); ready.remove(running); executed++; } } } /** * Finds the process with the shortest job of all the ready processes (based on a process * @param readyProcesses an array list of ready processes * @return returns the process' with the shortest burst time OR NULL if there are no ready * processes */ private ProcessDetails findShortestJob(Collection<ProcessDetails> readyProcesses) { return readyProcesses.stream().min(Comparator.comparingInt(ProcessDetails::getBurstTime)).orElse(null); } /** * Returns the computed schedule after calling scheduleProcesses(). */ public List<String> getSchedule() { return schedule; } public List<ProcessDetails> getProcesses() { return List.copyOf(processes); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/AgingScheduling.java
src/main/java/com/thealgorithms/scheduling/AgingScheduling.java
package com.thealgorithms.scheduling; import java.util.LinkedList; import java.util.Queue; /** * AgingScheduling is an algorithm designed to prevent starvation * by gradually increasing the priority of waiting tasks. * The longer a process waits, the higher its priority becomes. * * Use Case: Useful in systems with mixed workloads to avoid * lower-priority tasks being starved by higher-priority tasks. * * @author Hardvan */ public final class AgingScheduling { static class Task { String name; int waitTime; int priority; Task(String name, int priority) { this.name = name; this.priority = priority; this.waitTime = 0; } } private final Queue<Task> taskQueue; public AgingScheduling() { taskQueue = new LinkedList<>(); } /** * Adds a task to the scheduler with a given priority. * * @param name name of the task * @param priority priority of the task */ public void addTask(String name, int priority) { taskQueue.offer(new Task(name, priority)); } /** * Schedules the next task based on the priority and wait time. * The priority of a task increases with the time it spends waiting. * * @return name of the next task to be executed */ public String scheduleNext() { if (taskQueue.isEmpty()) { return null; } Task nextTask = taskQueue.poll(); nextTask.waitTime++; nextTask.priority += nextTask.waitTime; taskQueue.offer(nextTask); return nextTask.name; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/RRScheduling.java
src/main/java/com/thealgorithms/scheduling/RRScheduling.java
package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @author Md Asif Joardar * The Round-robin scheduling algorithm is a kind of preemptive First come, First Serve CPU * Scheduling algorithm. This can be understood here - * https://www.scaler.com/topics/round-robin-scheduling-in-os/ */ public class RRScheduling { private List<ProcessDetails> processes; private int quantumTime; RRScheduling(final List<ProcessDetails> processes, int quantumTime) { this.processes = processes; this.quantumTime = quantumTime; } public void scheduleProcesses() { evaluateTurnAroundTime(); evaluateWaitingTime(); } private void evaluateTurnAroundTime() { int processesNumber = processes.size(); if (processesNumber == 0) { return; } Queue<Integer> queue = new LinkedList<>(); queue.add(0); int currentTime = 0; // keep track of the time int completed = 0; int[] mark = new int[processesNumber]; Arrays.fill(mark, 0); mark[0] = 1; // a copy of burst time to store the remaining burst time int[] remainingBurstTime = new int[processesNumber]; for (int i = 0; i < processesNumber; i++) { remainingBurstTime[i] = processes.get(i).getBurstTime(); } while (completed != processesNumber) { int index = queue.poll(); if (remainingBurstTime[index] == processes.get(index).getBurstTime()) { currentTime = Math.max(currentTime, processes.get(index).getArrivalTime()); } if (remainingBurstTime[index] - quantumTime > 0) { remainingBurstTime[index] -= quantumTime; currentTime += quantumTime; } else { currentTime += remainingBurstTime[index]; processes.get(index).setTurnAroundTimeTime(currentTime - processes.get(index).getArrivalTime()); completed++; remainingBurstTime[index] = 0; } // If some process has arrived when this process was executing, insert them into the // queue. for (int i = 1; i < processesNumber; i++) { if (remainingBurstTime[i] > 0 && processes.get(i).getArrivalTime() <= currentTime && mark[i] == 0) { mark[i] = 1; queue.add(i); } } // If the current process has burst time remaining, push the process into the queue // again. if (remainingBurstTime[index] > 0) { queue.add(index); } // If the queue is empty, pick the first process from the list that is not completed. if (queue.isEmpty()) { for (int i = 1; i < processesNumber; i++) { if (remainingBurstTime[i] > 0) { mark[i] = 1; queue.add(i); break; } } } } } private void evaluateWaitingTime() { for (final var process : processes) { process.setWaitingTime(process.getTurnAroundTimeTime() - process.getBurstTime()); } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java
src/main/java/com/thealgorithms/scheduling/SRTFScheduling.java
package com.thealgorithms.scheduling; import com.thealgorithms.devutils.entities.ProcessDetails; import java.util.ArrayList; import java.util.List; /** * Implementation of Shortest Remaining Time First Scheduling Algorithm. * In the SRTF scheduling algorithm, the process with the smallest amount of time remaining until completion is selected to execute. * Example: * Consider the processes p1, p2 and the following table with info about their arrival and burst time: * Process | Burst Time | Arrival Time * P1 | 6 ms | 0 ms * P2 | 2 ms | 1 ms * In this example, P1 will be executed at time = 0 until time = 1 when P2 arrives. At time = 2, P2 will be executed until time = 4. At time 4, P2 is done, and P1 is executed again to be done. * That's a simple example of how the algorithm works. * More information you can find here -> https://en.wikipedia.org/wiki/Shortest_remaining_time */ public class SRTFScheduling { protected List<ProcessDetails> processes; protected List<String> ready; /** * Constructor * @param processes ArrayList of ProcessDetails given as input */ public SRTFScheduling(ArrayList<ProcessDetails> processes) { this.processes = new ArrayList<>(); ready = new ArrayList<>(); this.processes = processes; } public void evaluateScheduling() { int time = 0; int cr = 0; // cr=current running process, time= units of time int n = processes.size(); int[] remainingTime = new int[n]; /* calculating remaining time of every process and total units of time */ for (int i = 0; i < n; i++) { remainingTime[i] = processes.get(i).getBurstTime(); time += processes.get(i).getBurstTime(); } /* if the first process doesn't arrive at 0, we have more units of time */ if (processes.get(0).getArrivalTime() != 0) { time += processes.get(0).getArrivalTime(); } /* printing id of the process which is executed at every unit of time */ // if the first process doesn't arrive at 0, we print only \n until it arrives if (processes.get(0).getArrivalTime() != 0) { for (int i = 0; i < processes.get(0).getArrivalTime(); i++) { ready.add(null); } } for (int i = processes.get(0).getArrivalTime(); i < time; i++) { /* checking if there's a process with remaining time less than current running process. If we find it, then it executes. */ for (int j = 0; j < n; j++) { if (processes.get(j).getArrivalTime() <= i && (remainingTime[j] < remainingTime[cr] && remainingTime[j] > 0 || remainingTime[cr] == 0)) { cr = j; } } ready.add(processes.get(cr).getProcessId()); remainingTime[cr]--; } } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java
src/main/java/com/thealgorithms/scheduling/diskscheduling/LookScheduling.java
package com.thealgorithms.scheduling.diskscheduling; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * https://en.wikipedia.org/wiki/LOOK_algorithm * Look Scheduling algorithm implementation. * The Look algorithm moves the disk arm to the closest request in the current direction, * and once it processes all requests in that direction, it reverses the direction. */ public class LookScheduling { private final int maxTrack; private final int currentPosition; private boolean movingUp; private int farthestPosition; public LookScheduling(int startPosition, boolean initialDirection, int maxTrack) { this.currentPosition = startPosition; this.movingUp = initialDirection; this.maxTrack = maxTrack; } /** * Executes the Look Scheduling algorithm on the given list of requests. * * @param requests List of disk requests. * @return Order in which requests are processed. */ public List<Integer> execute(List<Integer> requests) { List<Integer> result = new ArrayList<>(); List<Integer> lower = new ArrayList<>(); List<Integer> upper = new ArrayList<>(); // Split requests into two lists based on their position relative to current position for (int request : requests) { if (request >= 0 && request < maxTrack) { if (request < currentPosition) { lower.add(request); } else { upper.add(request); } } } // Sort the requests Collections.sort(lower); Collections.sort(upper); // Process the requests depending on the initial moving direction if (movingUp) { // Process requests in the upward direction result.addAll(upper); if (!upper.isEmpty()) { farthestPosition = upper.get(upper.size() - 1); } // Reverse the direction and process downward movingUp = false; Collections.reverse(lower); result.addAll(lower); if (!lower.isEmpty()) { farthestPosition = Math.max(farthestPosition, lower.get(0)); } } else { // Process requests in the downward direction Collections.reverse(lower); result.addAll(lower); if (!lower.isEmpty()) { farthestPosition = lower.get(0); } // Reverse the direction and process upward movingUp = true; result.addAll(upper); if (!upper.isEmpty()) { farthestPosition = Math.max(farthestPosition, upper.get(upper.size() - 1)); } } return result; } public int getCurrentPosition() { return currentPosition; } public boolean isMovingUp() { return movingUp; } public int getFarthestPosition() { return farthestPosition; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java
src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularScanScheduling.java
package com.thealgorithms.scheduling.diskscheduling; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Circular Scan Scheduling (C-SCAN) is a disk scheduling algorithm that * works by moving the disk arm in one direction to service requests until * it reaches the end of the disk. Once it reaches the end, instead of reversing * direction like in the SCAN algorithm, the arm moves back to the starting point * without servicing any requests. This ensures a more uniform wait time for all * requests, especially those near the disk edges. The algorithm then continues in * the same direction, making it effective for balancing service time across all disk sectors. */ public class CircularScanScheduling { private int currentPosition; private boolean movingUp; private final int diskSize; public CircularScanScheduling(int startPosition, boolean movingUp, int diskSize) { this.currentPosition = startPosition; this.movingUp = movingUp; this.diskSize = diskSize; } public List<Integer> execute(List<Integer> requests) { if (requests.isEmpty()) { return new ArrayList<>(); // Return empty list if there are no requests } List<Integer> sortedRequests = new ArrayList<>(requests); Collections.sort(sortedRequests); List<Integer> result = new ArrayList<>(); if (movingUp) { // Moving up: process requests >= current position for (int request : sortedRequests) { if (request >= currentPosition && request < diskSize) { result.add(request); } } // Jump to the smallest request and continue processing from the start for (int request : sortedRequests) { if (request < currentPosition) { result.add(request); } } } else { // Moving down: process requests <= current position in reverse order for (int i = sortedRequests.size() - 1; i >= 0; i--) { int request = sortedRequests.get(i); if (request <= currentPosition) { result.add(request); } } // Jump to the largest request and continue processing in reverse order for (int i = sortedRequests.size() - 1; i >= 0; i--) { int request = sortedRequests.get(i); if (request > currentPosition) { result.add(request); } } } // Set final position to the last request processed if (!result.isEmpty()) { currentPosition = result.get(result.size() - 1); } return result; } public int getCurrentPosition() { return currentPosition; } public boolean isMovingUp() { return movingUp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java
src/main/java/com/thealgorithms/scheduling/diskscheduling/ScanScheduling.java
package com.thealgorithms.scheduling.diskscheduling; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * https://en.wikipedia.org/wiki/Elevator_algorithm * SCAN Scheduling algorithm implementation. * The SCAN algorithm moves the disk arm towards one end of the disk, servicing all requests * along the way until it reaches the end. Once it reaches the end, it reverses direction * and services the requests on its way back. * * This algorithm ensures that all requests are serviced in a fair manner, * while minimizing the seek time for requests located close to the current position * of the disk arm. * * The SCAN algorithm is particularly useful in environments with a large number of * disk requests, as it reduces the overall movement of the disk arm compared to */ public class ScanScheduling { private int headPosition; private int diskSize; private boolean movingUp; public ScanScheduling(int headPosition, boolean movingUp, int diskSize) { this.headPosition = headPosition; this.movingUp = movingUp; this.diskSize = diskSize; } public List<Integer> execute(List<Integer> requests) { // If the request list is empty, return an empty result if (requests.isEmpty()) { return new ArrayList<>(); } List<Integer> result = new ArrayList<>(); List<Integer> left = new ArrayList<>(); List<Integer> right = new ArrayList<>(); // Separate requests into those smaller than the current head position and those larger for (int request : requests) { if (request < headPosition) { left.add(request); } else { right.add(request); } } // Sort the requests Collections.sort(left); Collections.sort(right); // Simulate the disk head movement if (movingUp) { // Head moving upward, process right-side requests first result.addAll(right); // After reaching the end of the disk, reverse direction and process left-side requests result.add(diskSize - 1); // Simulate the head reaching the end of the disk Collections.reverse(left); result.addAll(left); } else { // Head moving downward, process left-side requests first Collections.reverse(left); result.addAll(left); // After reaching the start of the disk, reverse direction and process right-side requests result.add(0); // Simulate the head reaching the start of the disk result.addAll(right); } return result; } public int getHeadPosition() { return headPosition; } public boolean isMovingUp() { return movingUp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java
src/main/java/com/thealgorithms/scheduling/diskscheduling/CircularLookScheduling.java
package com.thealgorithms.scheduling.diskscheduling; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Circular Look Scheduling (C-LOOK) is a disk scheduling algorithm similar to * the C-SCAN algorithm but with a key difference. In C-LOOK, the disk arm also * moves in one direction to service requests, but instead of going all the way * to the end of the disk, it only goes as far as the furthest request in the * current direction. After servicing the last request in the current direction, * the arm immediately jumps back to the closest request on the other side without * moving to the disk's extreme ends. This reduces the unnecessary movement of the * disk arm, resulting in better performance compared to C-SCAN, while still * maintaining fair wait times for requests. */ public class CircularLookScheduling { private int currentPosition; private boolean movingUp; private final int maxCylinder; public CircularLookScheduling(int startPosition, boolean movingUp, int maxCylinder) { this.currentPosition = startPosition; this.movingUp = movingUp; this.maxCylinder = maxCylinder; } public List<Integer> execute(List<Integer> requests) { List<Integer> result = new ArrayList<>(); // Filter and sort valid requests in both directions List<Integer> upRequests = new ArrayList<>(); List<Integer> downRequests = new ArrayList<>(); for (int request : requests) { if (request >= 0 && request < maxCylinder) { if (request > currentPosition) { upRequests.add(request); } else if (request < currentPosition) { downRequests.add(request); } } } Collections.sort(upRequests); Collections.sort(downRequests); if (movingUp) { // Process all requests in the upward direction result.addAll(upRequests); // Jump to the lowest request and process all requests in the downward direction result.addAll(downRequests); } else { // Process all requests in the downward direction (in reverse order) Collections.reverse(downRequests); result.addAll(downRequests); // Jump to the highest request and process all requests in the upward direction (in reverse order) Collections.reverse(upRequests); result.addAll(upRequests); } // Update current position to the last processed request if (!result.isEmpty()) { currentPosition = result.get(result.size() - 1); } return result; } public int getCurrentPosition() { return currentPosition; } public boolean isMovingUp() { return movingUp; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java
src/main/java/com/thealgorithms/scheduling/diskscheduling/SSFScheduling.java
package com.thealgorithms.scheduling.diskscheduling; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** *https://en.wikipedia.org/wiki/Shortest_seek_first * Shortest Seek First (SFF) Scheduling algorithm implementation. * The SFF algorithm selects the next request to be serviced based on the shortest distance * from the current position of the disk arm. It continuously evaluates all pending requests * and chooses the one that requires the least amount of movement to service. * * This approach minimizes the average seek time, making it efficient in terms of response * time for individual requests. However, it may lead to starvation for requests located * further away from the current position of the disk arm. * * The SFF algorithm is particularly effective in systems where quick response time * is crucial, as it ensures that the most accessible requests are prioritized for servicing. */ public class SSFScheduling { private int currentPosition; public SSFScheduling(int currentPosition) { this.currentPosition = currentPosition; } public List<Integer> execute(Collection<Integer> requests) { List<Integer> result = new ArrayList<>(requests); List<Integer> orderedRequests = new ArrayList<>(); while (!result.isEmpty()) { int closest = findClosest(result); orderedRequests.add(closest); result.remove(Integer.valueOf(closest)); currentPosition = closest; } return orderedRequests; } private int findClosest(List<Integer> requests) { int minDistance = Integer.MAX_VALUE; int closest = -1; for (int request : requests) { int distance = Math.abs(currentPosition - request); if (distance < minDistance) { minDistance = distance; closest = request; } } return closest; } public int getCurrentPosition() { return currentPosition; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java
src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java
package com.thealgorithms.stacks; import java.util.NoSuchElementException; import java.util.Stack; /** * A class that implements a stack that gives the maximum element in O(1) time. * The mainStack is used to store the all the elements of the stack * While the maxStack stores the maximum elements * When we want to get a maximum element, we call the top of the maximum stack * * Problem: https://www.baeldung.com/cs/stack-constant-time */ public class GreatestElementConstantTime { private Stack<Integer> mainStack; // initialize a mainStack private Stack<Integer> maxStack; // initialize a maxStack /** * Constructs two empty stacks */ public GreatestElementConstantTime() { mainStack = new Stack<>(); maxStack = new Stack<>(); } /** * Pushes an element onto the top of the stack. * Checks if the element is the maximum or not * If so, then pushes to the maximum stack * @param data The element to be pushed onto the stack. */ public void push(int data) { if (mainStack.isEmpty()) { mainStack.push(data); maxStack.push(data); return; } mainStack.push(data); if (data > maxStack.peek()) { maxStack.push(data); } } /** * Pops an element from the stack. * Checks if the element to be popped is the maximum or not * If so, then pop from the minStack * * @throws NoSuchElementException if the stack is empty. */ public void pop() { if (mainStack.isEmpty()) { throw new NoSuchElementException("Stack is empty"); } int ele = mainStack.pop(); if (ele == maxStack.peek()) { maxStack.pop(); } } /** * Returns the maximum element present in the stack * * @return The element at the top of the maxStack, or null if the stack is empty. */ public Integer getMaximumElement() { if (maxStack.isEmpty()) { return null; } return maxStack.peek(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java
src/main/java/com/thealgorithms/stacks/SmallestElementConstantTime.java
package com.thealgorithms.stacks; import java.util.NoSuchElementException; import java.util.Stack; /** * A class that implements a stack that gives the minimum element in O(1) time. * The mainStack is used to store the all the elements of the stack * While the minStack stores the minimum elements * When we want to get a minimum element, we call the top of the minimum stack * * Problem: https://www.baeldung.com/cs/stack-constant-time */ public class SmallestElementConstantTime { private Stack<Integer> mainStack; // initialize a mainStack private Stack<Integer> minStack; // initialize a minStack /** * Constructs two empty stacks */ public SmallestElementConstantTime() { mainStack = new Stack<>(); minStack = new Stack<>(); } /** * Pushes an element onto the top of the stack. * Checks if the element is the minimum or not * If so, then pushes to the minimum stack * @param data The element to be pushed onto the stack. */ public void push(int data) { if (mainStack.isEmpty()) { mainStack.push(data); minStack.push(data); return; } mainStack.push(data); if (data < minStack.peek()) { minStack.push(data); } } /** * Pops an element from the stack. * Checks if the element to be popped is the minimum or not * If so, then pop from the minStack * * @throws NoSuchElementException if the stack is empty. */ public void pop() { if (mainStack.isEmpty()) { throw new NoSuchElementException("Stack is empty"); } int ele = mainStack.pop(); if (ele == minStack.peek()) { minStack.pop(); } } /** * Returns the minimum element present in the stack * * @return The element at the top of the minStack, or null if the stack is empty. */ public Integer getMinimumElement() { if (minStack.isEmpty()) { return null; } return minStack.peek(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
src/main/java/com/thealgorithms/stacks/DuplicateBrackets.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Class for detecting unnecessary or redundant brackets in a mathematical expression. * Assumes the expression is balanced (i.e., all opening brackets have matching closing brackets). */ public final class DuplicateBrackets { private DuplicateBrackets() { } /** * Checks for extra or redundant brackets in a given expression. * * @param expression the string representing the expression to be checked * @return true if there are extra or redundant brackets, false otherwise * @throws IllegalArgumentException if the input string is null */ public static boolean check(String expression) { if (expression == null) { throw new IllegalArgumentException("Input expression cannot be null."); } Stack<Character> stack = new Stack<>(); for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (ch == ')') { if (stack.isEmpty() || stack.peek() == '(') { return true; } while (!stack.isEmpty() && stack.peek() != '(') { stack.pop(); } if (!stack.isEmpty()) { stack.pop(); } } else { stack.push(ch); } } 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/stacks/NextSmallerElement.java
src/main/java/com/thealgorithms/stacks/NextSmallerElement.java
package com.thealgorithms.stacks; import java.util.Arrays; import java.util.Stack; /** * Utility class to find the next smaller element for each element in a given integer array. * * <p>The next smaller element for an element x is the first smaller element on the left side of x in the array. * If no such element exists, the result will contain -1 for that position.</p> * * <p>Example:</p> * <pre> * Input: {2, 7, 3, 5, 4, 6, 8} * Output: [-1, 2, 2, 3, 3, 4, 6] * </pre> */ public final class NextSmallerElement { private NextSmallerElement() { } /** * Finds the next smaller element for each element in the given array. * * @param array the input array of integers * @return an array where each element is replaced by the next smaller element on the left side in the input array, * or -1 if there is no smaller element. * @throws IllegalArgumentException if the input array is null */ public static int[] findNextSmallerElements(int[] array) { if (array == null) { throw new IllegalArgumentException("Input array cannot be null"); } int[] result = new int[array.length]; Stack<Integer> stack = new Stack<>(); // Initialize all elements to -1 (in case there is no smaller element) Arrays.fill(result, -1); // Traverse the array from left to right for (int i = 0; i < array.length; i++) { // Maintain the stack such that the top of the stack is the next smaller element while (!stack.isEmpty() && stack.peek() >= array[i]) { stack.pop(); } // If stack is not empty, then the top is the next smaller element if (!stack.isEmpty()) { result[i] = stack.peek(); } // Push the current element onto the stack stack.push(array[i]); } 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/stacks/DecimalToAnyUsingStack.java
src/main/java/com/thealgorithms/stacks/DecimalToAnyUsingStack.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Utility class for converting a non-negative decimal (base-10) integer * to its representation in another radix (base) between 2 and 16, inclusive. * * <p>This class uses a stack-based approach to reverse the digits obtained from * successive divisions by the target radix. * * <p>This class cannot be instantiated.</p> */ public final class DecimalToAnyUsingStack { private DecimalToAnyUsingStack() { } private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; /** * Convert a decimal number to another radix. * * @param number the number to be converted * @param radix the radix * @return the number represented in the new radix as a String * @throws IllegalArgumentException if number is negative or radix is not between 2 and 16 inclusive */ public static String convert(int number, int radix) { if (number < 0) { throw new IllegalArgumentException("Number must be non-negative."); } if (radix < 2 || radix > 16) { throw new IllegalArgumentException(String.format("Invalid radix: %d. Radix must be between 2 and 16.", radix)); } if (number == 0) { return "0"; } Stack<Character> digitStack = new Stack<>(); while (number > 0) { digitStack.push(DIGITS[number % radix]); number /= radix; } StringBuilder result = new StringBuilder(digitStack.size()); while (!digitStack.isEmpty()) { result.append(digitStack.pop()); } 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/stacks/PostfixEvaluator.java
src/main/java/com/thealgorithms/stacks/PostfixEvaluator.java
package com.thealgorithms.stacks; import java.util.Set; import java.util.Stack; /** * Evaluate a postfix (Reverse Polish) expression using a stack. * * <p>Example: Expression "5 6 + 2 *" results in 22. * <p>Applications: Used in calculators and expression evaluation in compilers. * * @author Hardvan */ public final class PostfixEvaluator { private PostfixEvaluator() { } private static final Set<String> OPERATORS = Set.of("+", "-", "*", "/"); /** * Evaluates the given postfix expression and returns the result. * * @param expression The postfix expression as a string with operands and operators separated by spaces. * @return The result of evaluating the postfix expression. * @throws IllegalArgumentException if the expression is invalid. */ public static int evaluatePostfix(String expression) { Stack<Integer> stack = new Stack<>(); for (String token : expression.split("\\s+")) { if (isOperator(token)) { int operand2 = stack.pop(); int operand1 = stack.pop(); stack.push(applyOperator(token, operand1, operand2)); } else { stack.push(Integer.valueOf(token)); } } if (stack.size() != 1) { throw new IllegalArgumentException("Invalid expression"); } return stack.pop(); } /** * Checks if the given token is an operator. * * @param token The token to check. * @return true if the token is an operator, false otherwise. */ private static boolean isOperator(String token) { return OPERATORS.contains(token); } /** * Applies the given operator to the two operands. * * @param operator The operator to apply. * @param a The first operand. * @param b The second operand. * @return The result of applying the operator to the operands. */ private static int applyOperator(String operator, int a, int b) { return switch (operator) { case "+" -> a + b; case "-" -> a - b; case "*" -> a * b; case "/" -> a / b; default -> throw new IllegalArgumentException("Invalid operator"); }; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java
src/main/java/com/thealgorithms/stacks/PalindromeWithStack.java
package com.thealgorithms.stacks; import java.util.LinkedList; /** * A class that implements a palindrome checker using a stack. * The stack is used to store the characters of the string, * which we will pop one-by-one to create the string in reverse. * * Reference: https://www.geeksforgeeks.org/check-whether-the-given-string-is-palindrome-using-stack/ */ public class PalindromeWithStack { private LinkedList<Character> stack; /** * Constructs an empty stack that stores characters. */ public PalindromeWithStack() { stack = new LinkedList<Character>(); } /** * Check if the string is a palindrome or not. * Convert all characters to lowercase and push them into a stack. * At the same time, build a string * Next, pop from the stack and build the reverse string * Finally, compare these two strings * * @param string The string to check if it is palindrome or not. */ public boolean checkPalindrome(String string) { // Create a StringBuilder to build the string from left to right StringBuilder stringBuilder = new StringBuilder(string.length()); // Convert all characters to lowercase String lowercase = string.toLowerCase(); // Iterate through the string for (int i = 0; i < lowercase.length(); ++i) { char c = lowercase.charAt(i); // Build the string from L->R stringBuilder.append(c); // Push to the stack stack.push(c); } // The stack contains the reverse order of the string StringBuilder reverseString = new StringBuilder(stack.size()); // Until the stack is not empty while (!stack.isEmpty()) { // Build the string from R->L reverseString.append(stack.pop()); } // Finally, compare the L->R string with the R->L string return reverseString.toString().equals(stringBuilder.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/stacks/StackUsingTwoQueues.java
src/main/java/com/thealgorithms/stacks/StackUsingTwoQueues.java
package com.thealgorithms.stacks; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; /** * A class that implements a stack using two queues. * This approach ensures that the stack's LIFO (Last In, First Out) behavior * is maintained by utilizing two queues for storage. * The mainQueue is used to store the elements of the stack, while the tempQueue * is used to temporarily store elements during the push operation. */ public class StackUsingTwoQueues { private Queue<Integer> mainQueue; private Queue<Integer> tempQueue; /** * Constructs an empty stack using two queues. */ public StackUsingTwoQueues() { mainQueue = new LinkedList<>(); tempQueue = new LinkedList<>(); } /** * Pushes an element onto the top of the stack. * The newly pushed element becomes the top of the stack. * * @param item The element to be pushed onto the stack. */ public void push(int item) { tempQueue.add(item); // Move all elements from the mainQueue to tempQueue to maintain LIFO order while (!mainQueue.isEmpty()) { tempQueue.add(mainQueue.remove()); } // Swap the names of the two queues Queue<Integer> swap = mainQueue; mainQueue = tempQueue; tempQueue = swap; // tempQueue is now empty } /** * Removes and returns the element at the top of the stack. * Throws an exception if the stack is empty. * * @return The element at the top of the stack. * @throws NoSuchElementException if the stack is empty. */ public int pop() { if (mainQueue.isEmpty()) { throw new NoSuchElementException("Stack is empty"); } return mainQueue.remove(); } /** * Returns the element at the top of the stack without removing it. * Returns null if the stack is empty. * * @return The element at the top of the stack, or null if the stack is empty. */ public Integer peek() { if (mainQueue.isEmpty()) { return null; } return mainQueue.peek(); } /** * Returns true if the stack is empty. * * @return true if the stack is empty; false otherwise. */ public boolean isEmpty() { return mainQueue.isEmpty(); } /** * Returns the number of elements in the stack. * * @return The size of the stack. */ public int size() { return mainQueue.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/stacks/CelebrityFinder.java
src/main/java/com/thealgorithms/stacks/CelebrityFinder.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Solves the celebrity problem using a stack-based algorithm. * * <p>Celebrity is someone known by everyone but doesn't know anyone else. * <p>Applications: Graph theory and social network analysis. * * @author Hardvan */ public final class CelebrityFinder { private CelebrityFinder() { } /** * Finds the celebrity in the given party matrix using a stack-based algorithm. * * @param party A 2D matrix where party[i][j] is 1 if i knows j, otherwise 0. * @return The index of the celebrity, or -1 if there is no celebrity. */ public static int findCelebrity(int[][] party) { // Push all people onto the stack Stack<Integer> stack = new Stack<>(); for (int i = 0; i < party.length; i++) { stack.push(i); } // Find the potential celebrity by comparing pairs while (stack.size() > 1) { int person1 = stack.pop(); int person2 = stack.pop(); if (party[person1][person2] == 1) { stack.push(person2); // person1 knows person2, so person2 might be the celebrity } else { stack.push(person1); // person1 doesn't know person2, so person1 might be the celebrity } } // Verify the candidate int candidate = stack.pop(); for (int i = 0; i < party.length; i++) { if (i != candidate && (party[candidate][i] == 1 || party[i][candidate] == 0)) { return -1; } } return candidate; } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/PostfixToInfix.java
src/main/java/com/thealgorithms/stacks/PostfixToInfix.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Postfix to Infix implementation via Stack * * Function: String getPostfixToInfix(String postfix) * Returns the Infix Expression for the given postfix parameter. * * Avoid using parentheses/brackets/braces for the postfix string. * Postfix Expressions don't require these. * * * @author nikslyon19 (Nikhil Bisht) * */ public final class PostfixToInfix { private PostfixToInfix() { } /** * Determines if a given character is a valid arithmetic operator. * * @param token the character to check * @return true if the character is an operator, false otherwise */ public static boolean isOperator(char token) { return token == '+' || token == '-' || token == '/' || token == '*' || token == '^'; } /** * Validates whether a given string is a valid postfix expression. * * A valid postfix expression must meet these criteria: * 1. It should have at least one operator and two operands. * 2. The number of operands should always be greater than the number of operators at any point in the traversal. * * @param postfix the postfix expression string to validate * @return true if the expression is valid, false otherwise */ public static boolean isValidPostfixExpression(String postfix) { if (postfix.length() == 1 && (Character.isAlphabetic(postfix.charAt(0)))) { return true; } if (postfix.length() < 3) { return false; // Postfix expression should have at least one operator and two operands } int operandCount = 0; int operatorCount = 0; for (char token : postfix.toCharArray()) { if (isOperator(token)) { operatorCount++; if (operatorCount >= operandCount) { return false; // Invalid: more operators than operands at any point } } else { operandCount++; } } return operandCount == operatorCount + 1; } /** * Converts a valid postfix expression to an infix expression. * * @param postfix the postfix expression to convert * @return the equivalent infix expression * @throws IllegalArgumentException if the postfix expression is invalid */ public static String getPostfixToInfix(String postfix) { if (postfix.isEmpty()) { return ""; } if (!isValidPostfixExpression(postfix)) { throw new IllegalArgumentException("Invalid Postfix Expression"); } Stack<String> stack = new Stack<>(); StringBuilder valueString = new StringBuilder(); for (char token : postfix.toCharArray()) { if (!isOperator(token)) { stack.push(Character.toString(token)); } else { String operandB = stack.pop(); String operandA = stack.pop(); valueString.append('(').append(operandA).append(token).append(operandB).append(')'); stack.push(valueString.toString()); valueString.setLength(0); } } return stack.pop(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/PrefixToInfix.java
src/main/java/com/thealgorithms/stacks/PrefixToInfix.java
package com.thealgorithms.stacks; import java.util.Stack; /** * Converts a prefix expression to an infix expression using a stack. * * The input prefix expression should consist of * valid operands (letters or digits) and operators (+, -, *, /, ^). * Parentheses are not required in the prefix string. */ public final class PrefixToInfix { private PrefixToInfix() { } /** * Determines if a given character is a valid arithmetic operator. * * @param token the character to check * @return true if the character is an operator, false otherwise */ public static boolean isOperator(char token) { return token == '+' || token == '-' || token == '/' || token == '*' || token == '^'; } /** * Converts a valid prefix expression to an infix expression. * * @param prefix the prefix expression to convert * @return the equivalent infix expression * @throws NullPointerException if the prefix expression is null */ public static String getPrefixToInfix(String prefix) { if (prefix == null) { throw new NullPointerException("Null prefix expression"); } if (prefix.isEmpty()) { return ""; } Stack<String> stack = new Stack<>(); // Iterate over the prefix expression from right to left for (int i = prefix.length() - 1; i >= 0; i--) { char token = prefix.charAt(i); if (isOperator(token)) { // Pop two operands from stack String operandA = stack.pop(); String operandB = stack.pop(); // Form the infix expression with parentheses String infix = "(" + operandA + token + operandB + ")"; // Push the resulting infix expression back onto the stack stack.push(infix); } else { // Push operand onto stack stack.push(Character.toString(token)); } } if (stack.size() != 1) { throw new ArithmeticException("Malformed prefix expression"); } return stack.pop(); // final element on the stack is the full infix expression } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java
src/main/java/com/thealgorithms/stacks/MinStackUsingSingleStack.java
package com.thealgorithms.stacks; import java.util.EmptyStackException; import java.util.Stack; /** * Min-Stack implementation using a single stack. * * This stack supports push, pop, and retrieving the minimum element * in constant time (O(1)) using a modified approach where the stack * stores both the element and the minimum value so far. * * @author Hardvan */ public class MinStackUsingSingleStack { private final Stack<long[]> stack = new Stack<>(); /** * Pushes a new value onto the stack. * Each entry stores both the value and the minimum value so far. * * @param value The value to be pushed onto the stack. */ public void push(int value) { if (stack.isEmpty()) { stack.push(new long[] {value, value}); } else { long minSoFar = Math.min(value, stack.peek()[1]); stack.push(new long[] {value, minSoFar}); } } /** * Removes the top element from the stack. */ public void pop() { if (!stack.isEmpty()) { stack.pop(); } } /** * Retrieves the top element from the stack. * * @return The top element of the stack. */ public int top() { if (!stack.isEmpty()) { return (int) stack.peek()[0]; } throw new EmptyStackException(); } /** * Retrieves the minimum element in the stack. * * @return The minimum element so far. */ public int getMin() { if (!stack.isEmpty()) { return (int) stack.peek()[1]; } throw new EmptyStackException(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false
TheAlgorithms/Java
https://github.com/TheAlgorithms/Java/blob/e945f1622490ff3b32e59d31780df27d0dc2ede4/src/main/java/com/thealgorithms/stacks/ValidParentheses.java
src/main/java/com/thealgorithms/stacks/ValidParentheses.java
package com.thealgorithms.stacks; import java.util.HashMap; import java.util.Map; import java.util.Stack; /** * Valid Parentheses Problem * * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', * determine if the input string is valid. * * An input string is valid if: * 1. Open brackets must be closed by the same type of brackets. * 2. Open brackets must be closed in the correct order. * 3. Every close bracket has a corresponding open bracket of the same type. * * Examples: * Input: "()" * Output: true * * Input: "()[]{}" * Output: true * * Input: "(]" * Output: false * * Input: "([)]" * Output: false * * @author Gokul45-45 */ public final class ValidParentheses { private ValidParentheses() { } /** * Checks if the given string has valid parentheses * * @param s the input string containing parentheses * @return true if valid, false otherwise */ public static boolean isValid(String s) { if (s == null || s.length() % 2 != 0) { return false; } Map<Character, Character> parenthesesMap = new HashMap<>(); parenthesesMap.put('(', ')'); parenthesesMap.put('{', '}'); parenthesesMap.put('[', ']'); Stack<Character> stack = new Stack<>(); for (char c : s.toCharArray()) { if (parenthesesMap.containsKey(c)) { // Opening bracket - push to stack stack.push(c); } else { // Closing bracket - check if it matches if (stack.isEmpty()) { return false; } char openBracket = stack.pop(); if (parenthesesMap.get(openBracket) != c) { return false; } } } // Stack should be empty if all brackets are matched return stack.isEmpty(); } }
java
MIT
e945f1622490ff3b32e59d31780df27d0dc2ede4
2026-01-04T14:45:56.733479Z
false