From 02ebe075d60622e63f6807a56907e99795e89ffe Mon Sep 17 00:00:00 2001 From: Aman Mohamed Ali <69119173+spidervirus@users.noreply.github.com> Date: Thu, 12 Nov 2026 13:21:37 +0400 Subject: [PATCH 01/19] fix(maths): correct coordinate subtraction in DistanceFormula.euclideanDistance (#7747) --- .../thealgorithms/maths/DistanceFormula.java | 2 +- .../maths/DistanceFormulaTest.java | 21 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/DistanceFormula.java b/src/main/java/com/thealgorithms/maths/DistanceFormula.java index f7e2c7629551..b6c09c2cdb82 100644 --- a/src/main/java/com/thealgorithms/maths/DistanceFormula.java +++ b/src/main/java/com/thealgorithms/maths/DistanceFormula.java @@ -6,7 +6,7 @@ private DistanceFormula() { public static double euclideanDistance(double x1, double y1, double x2, double y2) { double dX = Math.pow(x2 - x1, 2); - double dY = Math.pow(y2 - x1, 2); + double dY = Math.pow(y2 - y1, 2); return Math.sqrt(dX + dY); } diff --git a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java index 66f3b7b03938..d761326558a4 100644 --- a/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java +++ b/src/test/java/com/thealgorithms/maths/DistanceFormulaTest.java @@ -14,17 +14,32 @@ void euclideanTest1() { @Test void euclideanTest2() { - Assertions.assertEquals(7.0710678118654755, DistanceFormula.euclideanDistance(1, 3, 8, 0)); + Assertions.assertEquals(7.615773105863909, DistanceFormula.euclideanDistance(1, 3, 8, 0)); } @Test void euclideanTest3() { - Assertions.assertEquals(110.91911467371168, DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100)); + Assertions.assertEquals(105.07188015829927, DistanceFormula.euclideanDistance(2.4, 9.1, 55.1, 100)); } @Test void euclideanTest4() { - Assertions.assertEquals(19022.067605809836, DistanceFormula.euclideanDistance(1000, 13, 20000, 84)); + Assertions.assertEquals(19000.13265743163, DistanceFormula.euclideanDistance(1000, 13, 20000, 84)); + } + + @Test + void euclideanTestZeroDistance() { + Assertions.assertEquals(0.0, DistanceFormula.euclideanDistance(0, 0, 0, 0)); + } + + @Test + void euclideanTestPythagoreanTriple() { + Assertions.assertEquals(5.0, DistanceFormula.euclideanDistance(0, 0, 3, 4)); + } + + @Test + void euclideanTestNegativeCoordinates() { + Assertions.assertEquals(5.0, DistanceFormula.euclideanDistance(-1, -2, 2, 2)); } @Test From 3c4f19d4d847cdbee406137d6ddea88a3bcf8373 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 12 Nov 2026 09:25:23 +0000 Subject: [PATCH 02/19] chore(deps): bump github/codeql-action from 4.39.2 to 4.39.3 in /.github/workflows (#7750) chore(deps): bump github/codeql-action in /.github/workflows Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.2 to 4.39.3. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v4.39.2...v4.39.3) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 4.39.3 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 88c7618dc4f7..66d626f52876 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -30,7 +30,7 @@ jobs: distribution: 'temurin' - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.2 + uses: github/codeql-action/init@v4.39.3 with: languages: 'java-kotlin' @@ -38,7 +38,7 @@ jobs: run: mvn --batch-mode --update-snapshots verify - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.2 + uses: github/codeql-action/analyze@v4.39.3 with: category: "/language:java-kotlin" @@ -55,12 +55,12 @@ jobs: uses: actions/checkout@v7 - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.2 + uses: github/codeql-action/init@v4.39.3 with: languages: 'actions' - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.2 + uses: github/codeql-action/analyze@v4.39.3 with: category: "/language:actions" ... From 07c7ea317f67fe27c6830fc2cea652c65f19f225 Mon Sep 17 00:00:00 2001 From: Hardik K Date: Thu, 12 Nov 2026 14:59:32 +0530 Subject: [PATCH 03/19] fix(searches): add null safety and empty matrix handling to RowColumnWiseSorted2dArrayBinarySearch (#7725) * fix(searches): add null safety and empty matrix handling to RowColumnWiseSorted2dArrayBinarySearch * refactor(searches): scope validation to rectangular matrices per review --- ...owColumnWiseSorted2dArrayBinarySearch.java | 6 ++- ...lumnWiseSorted2dArrayBinarySearchTest.java | 52 +++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java index ecdcd36adf21..4b66cf2a220e 100644 --- a/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearch.java @@ -20,7 +20,7 @@ * doesn't exist in the array, an array * {-1, -1} will be returned. */ -public class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { +public final class RowColumnWiseSorted2dArrayBinarySearch implements MatrixSearchAlgorithm { @Override public > int[] find(T[][] matrix, T key) { @@ -28,6 +28,10 @@ public > int[] find(T[][] matrix, T key) { } public static > int[] search(T[][] matrix, T target) { + if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0 || target == null) { + return new int[] {-1, -1}; + } + int rowPointer = 0; // The pointer at 0th row int colPointer = matrix[0].length - 1; // The pointer at end column diff --git a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java index 8d1423cbeeb0..6740baeb3c89 100644 --- a/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java +++ b/src/test/java/com/thealgorithms/searches/RowColumnWiseSorted2dArrayBinarySearchTest.java @@ -237,4 +237,56 @@ public void rowColumnSorted2dArrayBinarySearchTestTallMatrixNotFound() { assertEquals(expected[0], ans[0]); assertEquals(expected[1], ans[1]); } + + @Test + public void testNullMatrixReturnsNotFound() { + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(null, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testEmptyMatrixReturnsNotFound() { + Integer[][] matrix = {}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testEmptyFirstRowReturnsNotFound() { + Integer[][] matrix = {{}}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testNullTargetReturnsNotFound() { + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(WIDE_RECTANGULAR_MATRIX, null); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testNullFirstRowReturnsNotFound() { + Integer[][] matrix = {null}; + int[] ans = RowColumnWiseSorted2dArrayBinarySearch.search(matrix, 5); + int[] expected = {-1, -1}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } + + @Test + public void testFindMethodThroughInterface() { + RowColumnWiseSorted2dArrayBinarySearch searcher = new RowColumnWiseSorted2dArrayBinarySearch(); + int[] ans = searcher.find(WIDE_RECTANGULAR_MATRIX, 35); + int[] expected = {1, 2}; + assertEquals(expected[0], ans[0]); + assertEquals(expected[1], ans[1]); + } } From e9957eaf70a4250c680be42952b96ced7859d028 Mon Sep 17 00:00:00 2001 From: S ROSHAN KUMAR Date: Fri, 13 Nov 2026 13:50:06 +0530 Subject: [PATCH 04/19] feat: add MoveZeroes algorithm with tests (#7738) feat: add move-zeroes algorithm with tests --- .../com/thealgorithms/misc/MoveZeroes.java | 28 +++++++++++++++ .../thealgorithms/misc/MoveZeroesTest.java | 36 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 src/main/java/com/thealgorithms/misc/MoveZeroes.java create mode 100644 src/test/java/com/thealgorithms/misc/MoveZeroesTest.java diff --git a/src/main/java/com/thealgorithms/misc/MoveZeroes.java b/src/main/java/com/thealgorithms/misc/MoveZeroes.java new file mode 100644 index 000000000000..31d6eb8dad98 --- /dev/null +++ b/src/main/java/com/thealgorithms/misc/MoveZeroes.java @@ -0,0 +1,28 @@ +package com.thealgorithms.misc; + +/** + * Moves all zeroes in an array to the end while maintaining the relative + * order of non-zero elements. The operation is performed in-place. + * + *

Example: [0, 1, 0, 3, 12] -> [1, 3, 12, 0, 0] + * + *

Time complexity: O(n), Space complexity: O(1) + * + * @see LeetCode #283 + */ +public final class MoveZeroes { + private MoveZeroes() { + } + + public static void moveZeroes(int[] nums) { + int insertPos = 0; + for (int num : nums) { + if (num != 0) { + nums[insertPos++] = num; + } + } + while (insertPos < nums.length) { + nums[insertPos++] = 0; + } + } +} diff --git a/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java b/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java new file mode 100644 index 000000000000..9c26e6b7340e --- /dev/null +++ b/src/test/java/com/thealgorithms/misc/MoveZeroesTest.java @@ -0,0 +1,36 @@ +package com.thealgorithms.misc; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +import org.junit.jupiter.api.Test; + +public class MoveZeroesTest { + + @Test + public void testMoveZeroes() { + int[] nums = {0, 1, 0, 3, 12}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {1, 3, 12, 0, 0}, nums); + } + + @Test + public void testNoZeroes() { + int[] nums = {1, 2, 3}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {1, 2, 3}, nums); + } + + @Test + public void testAllZeroes() { + int[] nums = {0, 0, 0}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {0, 0, 0}, nums); + } + + @Test + public void testSingleElement() { + int[] nums = {0}; + MoveZeroes.moveZeroes(nums); + assertArrayEquals(new int[] {0}, nums); + } +} From 2f04e814eeb7fcf1af1c680ac29934bbb4fb23b1 Mon Sep 17 00:00:00 2001 From: hindAlsh Date: Fri, 13 Nov 2026 01:28:35 -0700 Subject: [PATCH 05/19] Add ChaCha20 stream cipher (#7754) * Add ChaCha20 stream cipher This implementation is intended for educational purposes and should not be used as a replacement for a vetted cryptographic library in production. * Test ChaCha20 implementation * Add test for ChaCha20 handling partial blocks * Refactor CONSTANTS and littleEndianInt method * Refactor ChaCha20Test for clarity and readability Refactored nonce and expected byte array initialization for clarity. Updated test methods to improve readability by reducing line breaks. --- .../com/thealgorithms/ciphers/ChaCha20.java | 136 ++++++++++++++++++ .../thealgorithms/ciphers/ChaCha20Test.java | 92 ++++++++++++ 2 files changed, 228 insertions(+) create mode 100644 src/main/java/com/thealgorithms/ciphers/ChaCha20.java create mode 100644 src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java diff --git a/src/main/java/com/thealgorithms/ciphers/ChaCha20.java b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java new file mode 100644 index 000000000000..5f9906d406d4 --- /dev/null +++ b/src/main/java/com/thealgorithms/ciphers/ChaCha20.java @@ -0,0 +1,136 @@ +package com.thealgorithms.ciphers; + +import java.util.Objects; + +/** + * Implements the ChaCha20 stream cipher described in RFC 8439. + * + *

This implementation is intended for educational purposes and should not + * be used as a replacement for a vetted cryptographic library in production. + * + * @see RFC 8439 + */ +public final class ChaCha20 { + + private static final int BLOCK_SIZE = 64; + private static final long MAX_COUNTER = 0xFFFF_FFFFL; + private static final int[] CONSTANTS = {0x61707865, 0x3320646e, 0x79622d32, 0x6b206574}; + + private ChaCha20() { + // Utility class + } + + /** + * Encrypts bytes with ChaCha20. Decryption uses the same operation. + * + * @param input plaintext bytes; must not be {@code null} + * @param key 32-byte key + * @param nonce 12-byte nonce + * @param initialCounter unsigned 32-bit initial block counter + * @return encrypted bytes + * @throws NullPointerException if an argument is {@code null} + * @throws IllegalArgumentException if a key, nonce, or counter is invalid, + * or the counter would overflow while processing the input + */ + public static byte[] encrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) { + validateInputs(input, key, nonce, initialCounter); + + long blockCount = (input.length + (long) BLOCK_SIZE - 1) / BLOCK_SIZE; + if (blockCount > 0 && initialCounter > MAX_COUNTER - (blockCount - 1)) { + throw new IllegalArgumentException("Counter would overflow"); + } + + byte[] output = new byte[input.length]; + for (int offset = 0; offset < input.length; offset += BLOCK_SIZE) { + long counter = initialCounter + offset / BLOCK_SIZE; + byte[] keyStream = block(key, nonce, counter); + int bytesToProcess = Math.min(BLOCK_SIZE, input.length - offset); + + for (int i = 0; i < bytesToProcess; i++) { + output[offset + i] = (byte) (input[offset + i] ^ keyStream[i]); + } + } + return output; + } + + /** + * Decrypts bytes with ChaCha20. This is identical to encryption. + * + * @param input ciphertext bytes; must not be {@code null} + * @param key 32-byte key + * @param nonce 12-byte nonce + * @param initialCounter unsigned 32-bit initial block counter + * @return decrypted bytes + */ + public static byte[] decrypt(byte[] input, byte[] key, byte[] nonce, long initialCounter) { + return encrypt(input, key, nonce, initialCounter); + } + + private static void validateInputs(byte[] input, byte[] key, byte[] nonce, long counter) { + Objects.requireNonNull(input, "input must not be null"); + Objects.requireNonNull(key, "key must not be null"); + Objects.requireNonNull(nonce, "nonce must not be null"); + + if (key.length != 32) { + throw new IllegalArgumentException("Key must be 32 bytes"); + } + if (nonce.length != 12) { + throw new IllegalArgumentException("Nonce must be 12 bytes"); + } + if (counter < 0 || counter > MAX_COUNTER) { + throw new IllegalArgumentException("Counter must be an unsigned 32-bit value"); + } + } + + private static byte[] block(byte[] key, byte[] nonce, long counter) { + int[] state = new int[16]; + System.arraycopy(CONSTANTS, 0, state, 0, CONSTANTS.length); + + for (int i = 0; i < 8; i++) { + state[4 + i] = littleEndianInt(key, i * 4); + } + + state[12] = (int) counter; + state[13] = littleEndianInt(nonce, 0); + state[14] = littleEndianInt(nonce, 4); + state[15] = littleEndianInt(nonce, 8); + + int[] workingState = state.clone(); + for (int i = 0; i < 10; i++) { + quarterRound(workingState, 0, 4, 8, 12); + quarterRound(workingState, 1, 5, 9, 13); + quarterRound(workingState, 2, 6, 10, 14); + quarterRound(workingState, 3, 7, 11, 15); + + quarterRound(workingState, 0, 5, 10, 15); + quarterRound(workingState, 1, 6, 11, 12); + quarterRound(workingState, 2, 7, 8, 13); + quarterRound(workingState, 3, 4, 9, 14); + } + + byte[] output = new byte[BLOCK_SIZE]; + for (int i = 0; i < workingState.length; i++) { + int word = workingState[i] + state[i]; + output[i * 4] = (byte) word; + output[i * 4 + 1] = (byte) (word >>> 8); + output[i * 4 + 2] = (byte) (word >>> 16); + output[i * 4 + 3] = (byte) (word >>> 24); + } + return output; + } + + static void quarterRound(int[] state, int a, int b, int c, int d) { + state[a] += state[b]; + state[d] = Integer.rotateLeft(state[d] ^ state[a], 16); + state[c] += state[d]; + state[b] = Integer.rotateLeft(state[b] ^ state[c], 12); + state[a] += state[b]; + state[d] = Integer.rotateLeft(state[d] ^ state[a], 8); + state[c] += state[d]; + state[b] = Integer.rotateLeft(state[b] ^ state[c], 7); + } + + private static int littleEndianInt(byte[] bytes, int offset) { + return (bytes[offset] & 0xFF) | ((bytes[offset + 1] & 0xFF) << 8) | ((bytes[offset + 2] & 0xFF) << 16) | ((bytes[offset + 3] & 0xFF) << 24); + } +} diff --git a/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java b/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java new file mode 100644 index 000000000000..61d7c17ec663 --- /dev/null +++ b/src/test/java/com/thealgorithms/ciphers/ChaCha20Test.java @@ -0,0 +1,92 @@ +package com.thealgorithms.ciphers; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class ChaCha20Test { + + @Test + void quarterRoundMatchesRfc8439Vector() { + int[] state = {0x11111111, 0x01020304, 0x9b8d6f43, 0x01234567}; + + ChaCha20.quarterRound(state, 0, 1, 2, 3); + + assertArrayEquals(new int[] {0xea2a92f4, 0xcb1cf8ce, 0x4581472e, 0x5881c4bb}, state); + } + + @Test + void encryptingZeroesMatchesRfc8439BlockVector() { + byte[] key = new byte[32]; + for (int i = 0; i < key.length; i++) { + key[i] = (byte) i; + } + + byte[] nonce = {0, 0, 0, 9, 0, 0, 0, 0x4a, 0, 0, 0, 0}; + byte[] expected = {0x10, (byte) 0xf1, (byte) 0xe7, (byte) 0xe4, (byte) 0xd1, 0x3b, 0x59, 0x15, 0x50, 0x0f, (byte) 0xdd, 0x1f, (byte) 0xa3, 0x20, 0x71, (byte) 0xc4, (byte) 0xc7, (byte) 0xd1, (byte) 0xf4, (byte) 0xc7, 0x33, (byte) 0xc0, 0x68, 0x03, 0x04, 0x22, (byte) 0xaa, (byte) 0x9a, + (byte) 0xc3, (byte) 0xd4, 0x6c, 0x4e, (byte) 0xd2, (byte) 0x82, 0x64, 0x46, 0x07, (byte) 0x9f, (byte) 0xaa, 0x09, 0x14, (byte) 0xc2, (byte) 0xd7, 0x05, (byte) 0xd9, (byte) 0x8b, 0x02, (byte) 0xa2, (byte) 0xb5, 0x12, (byte) 0x9c, (byte) 0xd1, (byte) 0xde, 0x16, 0x4e, (byte) 0xb9, + (byte) 0xcb, (byte) 0xd0, (byte) 0x83, (byte) 0xe8, (byte) 0xa2, 0x50, 0x3c, 0x4e}; + + byte[] actual = ChaCha20.encrypt(new byte[64], key, nonce, 1); + + assertArrayEquals(expected, actual); + } + + @Test + void decryptRestoresInputAcrossMultipleBlocks() { + byte[] input = new byte[130]; + for (int i = 0; i < input.length; i++) { + input[i] = (byte) (i * 3); + } + + byte[] key = new byte[32]; + byte[] nonce = new byte[12]; + + byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 7); + byte[] decrypted = ChaCha20.decrypt(encrypted, key, nonce, 7); + + assertArrayEquals(input, decrypted); + } + + @Test + void handlesPartialBlocksAroundBlockBoundary() { + for (int length : new int[] {1, 63, 65}) { + byte[] input = new byte[length]; + for (int i = 0; i < input.length; i++) { + input[i] = (byte) (i + 1); + } + + byte[] key = new byte[32]; + byte[] nonce = new byte[12]; + byte[] encrypted = ChaCha20.encrypt(input, key, nonce, 0); + + assertArrayEquals(input, ChaCha20.decrypt(encrypted, key, nonce, 0)); + } + } + + @Test + void emptyInputReturnsEmptyOutput() { + assertArrayEquals(new byte[0], ChaCha20.encrypt(new byte[0], new byte[32], new byte[12], 1)); + } + + @Test + void maximumCounterCanProcessOneBlock() { + byte[] input = new byte[64]; + + assertArrayEquals(input, ChaCha20.decrypt(ChaCha20.encrypt(input, new byte[32], new byte[12], 0xFFFF_FFFFL), new byte[32], new byte[12], 0xFFFF_FFFFL)); + } + + @Test + void counterOverflowIsRejected() { + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[65], new byte[32], new byte[12], 0xFFFF_FFFFL)); + } + + @Test + void invalidKeyNonceAndCounterAreRejected() { + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[31], new byte[12], 0)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[11], 0)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], -1)); + assertThrows(IllegalArgumentException.class, () -> ChaCha20.encrypt(new byte[1], new byte[32], new byte[12], 0x1_0000_0000L)); + } +} From 402d3b056554cbb973c488941df0307b257bdc1b Mon Sep 17 00:00:00 2001 From: S ROSHAN KUMAR Date: Sat, 14 Nov 2026 14:44:29 +0530 Subject: [PATCH 06/19] feat: add RightSideViewOfBinaryTree algorithm with tests (#7734) * feat: add RightSideViewOfBinaryTree algorithm with tests * fix: correct input array for testRightSkewedTree --- .../trees/RightSideViewOfBinaryTree.java | 56 +++++++++++++++++ .../trees/RightSideViewOfBinaryTreeTest.java | 60 +++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java create mode 100644 src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java diff --git a/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java new file mode 100644 index 000000000000..6bb965aad4d6 --- /dev/null +++ b/src/main/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTree.java @@ -0,0 +1,56 @@ +package com.thealgorithms.datastructures.trees; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + +/** + * Given the root of a binary tree, returns the values of the nodes visible + * from the right side (the last node of each level in a level-order traversal). + * + *

Example: + *

+ *      1
+ *     / \
+ *    2   3
+ *     \   \
+ *      5   4
+ * Right side view: [1, 3, 4]
+ * 
+ * + *

Time complexity: O(n), Space complexity: O(n) + * + * @see LeetCode #199 + */ +public final class RightSideViewOfBinaryTree { + private RightSideViewOfBinaryTree() { + } + + public static List rightSideView(BinaryTree.Node root) { + List result = new ArrayList<>(); + if (root == null) { + return result; + } + + Queue queue = new LinkedList<>(); + queue.add(root); + + while (!queue.isEmpty()) { + int levelSize = queue.size(); + for (int i = 0; i < levelSize; i++) { + BinaryTree.Node node = queue.poll(); + if (i == levelSize - 1) { + result.add(node.data); + } + if (node.left != null) { + queue.add(node.left); + } + if (node.right != null) { + queue.add(node.right); + } + } + } + return result; + } +} diff --git a/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java b/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java new file mode 100644 index 000000000000..ded92d4d8de5 --- /dev/null +++ b/src/test/java/com/thealgorithms/datastructures/trees/RightSideViewOfBinaryTreeTest.java @@ -0,0 +1,60 @@ +package com.thealgorithms.datastructures.trees; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class RightSideViewOfBinaryTreeTest { + + @Test + public void testNullRoot() { + assertEquals(Collections.emptyList(), RightSideViewOfBinaryTree.rightSideView(null)); + } + + @Test + public void testSingleNode() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1}); + assertEquals(List.of(1), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + / \ + 2 3 + \ \ + 5 4 + */ + @Test + public void testRightSideView() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, 3, null, 5, null, 4}); + assertEquals(List.of(1, 3, 4), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + / + 2 + / + 3 + */ + @Test + public void testLeftSkewedTree() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, 2, null, 3}); + assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root)); + } + + /* + 1 + \ + 2 + \ + 3 + */ + @Test + public void testRightSkewedTree() { + final BinaryTree.Node root = TreeTestUtils.createTree(new Integer[] {1, null, 2, null, 3}); + assertEquals(List.of(1, 2, 3), RightSideViewOfBinaryTree.rightSideView(root)); + } +} From 401e25388def688d457ccab49dd84dd97d9d1b49 Mon Sep 17 00:00:00 2001 From: Hardik K Date: Sat, 14 Nov 2026 14:48:41 +0530 Subject: [PATCH 07/19] fix(searches): fix boundary safety and null checks in SaddlebackSearch (#7726) --- .../searches/SaddlebackSearch.java | 25 ++++++++-- .../searches/SaddlebackSearchTest.java | 49 +++++++++++++++++++ 2 files changed, 69 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java index 192c4d26c735..9455636a4c9c 100644 --- a/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java +++ b/src/main/java/com/thealgorithms/searches/SaddlebackSearch.java @@ -19,24 +19,39 @@ private SaddlebackSearch() { } /** - * This method performs Saddleback Search + * Searches for a key in a row-wise and column-wise sorted 2D array starting from the bottom-left corner. + * + * @param arr The sorted matrix. + * @param key The element to search for. + * @throws IllegalArgumentException if the array is null or empty. + * @return The index (row and column) of the element if found. Else returns {-1, -1}. + */ + public static int[] find(int[][] arr, int key) { + if (arr == null || arr.length == 0) { + throw new IllegalArgumentException("Array is empty"); + } + return find(arr, arr.length - 1, 0, key); + } + + /** + * This method performs Saddleback Search starting from the specified row and column. * * @param arr The **Sorted** array in which we will search the element. * @param row the current row. * @param col the current column. * @param key the element that we want to search for. - * @throws IllegalArgumentException if the array is empty. + * @throws IllegalArgumentException if the array is null or empty. * @return The index(row and column) of the element if found. Else returns * -1 -1. */ - static int[] find(int[][] arr, int row, int col, int key) { - if (arr.length == 0) { + public static int[] find(int[][] arr, int row, int col, int key) { + if (arr == null || arr.length == 0) { throw new IllegalArgumentException("Array is empty"); } // array to store the answer row and column int[] ans = {-1, -1}; - if (row < 0 || col >= arr[row].length) { + if (row < 0 || row >= arr.length || arr[row] == null || col < 0 || col >= arr[row].length) { return ans; } if (arr[row][col] == key) { diff --git a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java index ec22cbf38152..e4e6b2bf107d 100644 --- a/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java +++ b/src/test/java/com/thealgorithms/searches/SaddlebackSearchTest.java @@ -82,4 +82,53 @@ void testFindSingleElementNotExists() { int[] result = SaddlebackSearch.find(arr, 0, 0, 10); assertArrayEquals(new int[] {-1, -1}, result, "Element 10 should not be found in single element array"); } + + /** + * Test convenience method searching from the bottom-left corner automatically. + */ + @Test + void testFindWithConvenienceMethod() { + int[][] arr = {{-10, -5, -3, 4, 9}, {-6, -2, 0, 5, 10}, {-4, -1, 1, 6, 12}, {2, 3, 7, 8, 13}, {100, 120, 130, 140, 150}}; + int[] result = SaddlebackSearch.find(arr, 4); + assertArrayEquals(new int[] {0, 3}, result, "Element 4 should be found at (0, 3) using convenience overload"); + } + + /** + * Test searching in a null array throws IllegalArgumentException. + */ + @Test + void testFindWithNullArray() { + assertThrows(IllegalArgumentException.class, () -> SaddlebackSearch.find(null, 4)); + assertThrows(IllegalArgumentException.class, () -> SaddlebackSearch.find(null, 0, 0, 4)); + } + + /** + * Test row index out of bounds returns {-1, -1}. + */ + @Test + void testFindWithRowOutOfBounds() { + int[][] arr = {{1, 2}, {3, 4}}; + int[] result = SaddlebackSearch.find(arr, 5, 0, 3); + assertArrayEquals(new int[] {-1, -1}, result, "Row index out of bounds should return {-1, -1}"); + } + + /** + * Test negative column index returns {-1, -1}. + */ + @Test + void testFindWithNegativeColumn() { + int[][] arr = {{1, 2}, {3, 4}}; + int[] result = SaddlebackSearch.find(arr, 1, -1, 3); + assertArrayEquals(new int[] {-1, -1}, result, "Negative column index should return {-1, -1}"); + } + + /** + * Test null row in matrix returns {-1, -1} safely. + */ + @Test + void testFindWithNullRowInMatrix() { + int[][] arr = {{1, 2}, null, {5, 6}}; + int[] result = SaddlebackSearch.find(arr, 1, 0, 5); + assertArrayEquals(new int[] {-1, -1}, result, "Null row in matrix should safely return {-1, -1}"); + } } From a0062057ff1f346b9d6324e732bc84b6d9d32ed2 Mon Sep 17 00:00:00 2001 From: Prasad Pitke <120767959+Prasad-Pitke@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:20:39 +0530 Subject: [PATCH 08/19] Detect overflow in Pow.pow (#7752) Use Math.multiplyExact for overflow handling in pow --- src/main/java/com/thealgorithms/maths/Pow.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/maths/Pow.java b/src/main/java/com/thealgorithms/maths/Pow.java index 377b37ac4569..33dda5ba2ddc 100644 --- a/src/main/java/com/thealgorithms/maths/Pow.java +++ b/src/main/java/com/thealgorithms/maths/Pow.java @@ -22,6 +22,7 @@ private Pow() { * @param b the exponent to which the base {@code a} is raised. Must be a non-negative integer. * @return the result of {@code a}{@code b} as a {@code long}. * @throws IllegalArgumentException if {@code b} is negative. + * @throws ArithmeticException if the result overflows a {@code long}. */ public static long pow(int a, int b) { if (b < 0) { @@ -29,7 +30,7 @@ public static long pow(int a, int b) { } long result = 1; for (int i = 1; i <= b; i++) { - result *= a; + result = Math.multiplyExact(result, (long) a); } return result; } From 33f6e94cf1c3800f34c945061bbcbed0f8692e7f Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:03:49 +0200 Subject: [PATCH 09/19] chore(deps): bump org.apache.commons:commons-lang3 from 3.21.0 to 3.22.0 (#7759) Bumps org.apache.commons:commons-lang3 from 3.21.0 to 3.22.0. --- updated-dependencies: - dependency-name: org.apache.commons:commons-lang3 dependency-version: 3.22.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2af08520649a..f33ae0f435a7 100644 --- a/pom.xml +++ b/pom.xml @@ -48,7 +48,7 @@ org.apache.commons commons-lang3 - 3.21.0 + 3.22.0 org.apache.commons From b42e5df87251019f8836b2799ced4c6e20c4c6f8 Mon Sep 17 00:00:00 2001 From: Oleksandr Klymenko Date: Tue, 17 Nov 2026 19:45:52 +0200 Subject: [PATCH 10/19] feat: add TimestampOrderChecker, out of order and duplicate timestamps (#7733) Windowed algorithms assume time moves forward. When it does not, nothing fails loudly: a window holds samples that never coexisted, a rate is computed over a negative interval, a duplicate is counted twice. Retries, buffers flushed after a reconnect, several producers writing into one topic and a clock stepped backwards all cause this, and the cheap defence is to check the order explicitly. Each timestamp is compared with the previous one and classified as INCREASING, DUPLICATE or BACKWARDS. The checker only reports, it does not reorder or drop anything, so lastTimestamp is always the most recent sample, not the largest. It also keeps the worst backwards step, which is what you need to size a reordering buffer. O(1) time per sample and O(1) state; non-finite timestamps are refused. Tests: the first timestamp is always accepted, an ordered stream has no violations, duplicates and backwards steps are counted separately, the worst step is the largest one and not the last one, the stream is not reordered, scan returns one verdict per timestamp, and reset restores the initial state. Signed-off-by: alxkm <19151554+alxkm@users.noreply.github.com> Co-authored-by: alxkm <19151554+alxkm@users.noreply.github.com> --- .../streaming/TimestampOrderChecker.java | 203 ++++++++++++++++++ .../streaming/TimestampOrderCheckerTest.java | 139 ++++++++++++ 2 files changed, 342 insertions(+) create mode 100644 src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java create mode 100644 src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java diff --git a/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java new file mode 100644 index 000000000000..b220c82542d4 --- /dev/null +++ b/src/main/java/com/thealgorithms/streaming/TimestampOrderChecker.java @@ -0,0 +1,203 @@ +package com.thealgorithms.streaming; + +/** + * Watches the timestamps of a stream for samples that arrive out of order or twice. + * + *

Every windowed algorithm assumes that time moves forward. When it does not, nothing crashes: + * the window simply holds samples that never coexisted, a rate is computed over a negative interval, + * and a duplicate counts twice in an average. Retries, buffers flushed after a reconnect, several + * producers writing into one topic and a clock stepped backwards all produce exactly that, and the + * only cheap defence is to check the order explicitly. + * + *

Each timestamp is compared with the one immediately before it and classified as + * {@link Order#INCREASING}, {@link Order#DUPLICATE} or {@link Order#BACKWARDS}. The checker reports, + * it does not reorder or drop anything, so {@link #lastTimestamp()} is always the most recent sample + * and not the largest one seen. + * + *

Besides the counters it keeps the worst backwards step, which is what a caller needs in order to + * size a reordering buffer: a stream whose worst violation is 20 milliseconds can be repaired by + * holding samples for 20 milliseconds, while one that jumps back an hour cannot be repaired at all. + * + *

Usage

+ * + *
{@code
+ * TimestampOrderChecker checker = new TimestampOrderChecker();
+ * for (double timestamp : timestamps) {
+ *     if (checker.accept(timestamp).isViolation()) {
+ *         quarantine(timestamp);
+ *     }
+ * }
+ * }
+ * + *

Each sample costs O(1) time and the checker keeps O(1) state. This class is not thread-safe. + * + * @see Monotonic function + */ +public final class TimestampOrderChecker { + + private double lastTimestamp; + private double worstBackwardsStep; + private boolean started; + private long count; + private long duplicateCount; + private long backwardsCount; + private Order lastOrder = Order.INCREASING; + + /** + * Feeds the timestamp of one sample. + * + * @param timestamp when the sample arrived + * @return how this timestamp relates to the previous one; the first one is always + * {@link Order#INCREASING} + * @throws IllegalArgumentException if {@code timestamp} is NaN or infinite + */ + public Order accept(double timestamp) { + if (!Double.isFinite(timestamp)) { + throw new IllegalArgumentException("Timestamps must be finite, but was " + timestamp); + } + + Order order = Order.INCREASING; + if (started) { + if (timestamp == lastTimestamp) { + order = Order.DUPLICATE; + duplicateCount++; + } else if (timestamp < lastTimestamp) { + order = Order.BACKWARDS; + backwardsCount++; + worstBackwardsStep = Math.max(worstBackwardsStep, lastTimestamp - timestamp); + } + } + + lastTimestamp = timestamp; + started = true; + count++; + lastOrder = order; + return order; + } + + /** + * Runs the checker over a whole series of timestamps. + * + * @param timestamps the timestamps to inspect + * @return a new array of the same length holding the verdict for every timestamp + * @throws IllegalArgumentException if a timestamp is NaN or infinite + * @throws NullPointerException if {@code timestamps} is {@code null} + */ + public Order[] scan(double[] timestamps) { + Order[] verdicts = new Order[timestamps.length]; + for (int i = 0; i < timestamps.length; i++) { + verdicts[i] = accept(timestamps[i]); + } + return verdicts; + } + + /** + * Returns the verdict on the most recent timestamp. + * + * @return the last verdict, {@link Order#INCREASING} before the first timestamp + */ + public Order lastOrder() { + return lastOrder; + } + + /** + * Tells whether every timestamp so far moved forward. + * + * @return {@code true} if neither a duplicate nor a backwards step has been seen + */ + public boolean isOrdered() { + return duplicateCount == 0 && backwardsCount == 0; + } + + /** + * Returns the timestamp of the most recent sample, which is not necessarily the largest one seen. + * + * @return the last timestamp + * @throws IllegalStateException if no timestamp has been accepted yet + */ + public double lastTimestamp() { + if (!started) { + throw new IllegalStateException("The checker has not seen any timestamp yet"); + } + return lastTimestamp; + } + + /** + * Returns the largest distance a timestamp ever jumped backwards, which is how long a reordering + * buffer would have to hold a sample to repair this stream. + * + * @return the worst backwards step, {@code 0} if the stream never went backwards + */ + public double worstBackwardsStep() { + return worstBackwardsStep; + } + + /** + * Returns how many timestamps have been inspected since the last reset. + * + * @return the sample count + */ + public long count() { + return count; + } + + /** + * Returns how many timestamps repeated the one before them. + * + * @return the duplicate count + */ + public long duplicateCount() { + return duplicateCount; + } + + /** + * Returns how many timestamps were smaller than the one before them. + * + * @return the backwards count + */ + public long backwardsCount() { + return backwardsCount; + } + + /** + * Forgets every timestamp seen so far. + */ + public void reset() { + lastTimestamp = 0.0; + worstBackwardsStep = 0.0; + started = false; + count = 0; + duplicateCount = 0; + backwardsCount = 0; + lastOrder = Order.INCREASING; + } + + @Override + public String toString() { + return "TimestampOrderChecker{samples=" + count + ", duplicates=" + duplicateCount + ", backwards=" + backwardsCount + ", worstStep=" + worstBackwardsStep + "}"; + } + + /** + * How a timestamp relates to the one before it. + */ + public enum Order { + + /** The timestamp moved forward, which is the only healthy case. */ + INCREASING, + + /** The timestamp repeats the previous one. */ + DUPLICATE, + + /** The timestamp is older than the previous one. */ + BACKWARDS; + + /** + * Tells whether this verdict reports a broken timeline. + * + * @return {@code true} for {@link #DUPLICATE} and {@link #BACKWARDS} + */ + public boolean isViolation() { + return this != INCREASING; + } + } +} diff --git a/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java b/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java new file mode 100644 index 000000000000..43867ccd15b6 --- /dev/null +++ b/src/test/java/com/thealgorithms/streaming/TimestampOrderCheckerTest.java @@ -0,0 +1,139 @@ +package com.thealgorithms.streaming; + +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 com.thealgorithms.streaming.TimestampOrderChecker.Order; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class TimestampOrderCheckerTest { + + @ParameterizedTest + @ValueSource(doubles = {Double.NaN, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY}) + void rejectsNonFiniteTimestamps(double timestamp) { + TimestampOrderChecker checker = new TimestampOrderChecker(); + assertThrows(IllegalArgumentException.class, () -> checker.accept(timestamp)); + } + + @Test + void startsEmpty() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + assertEquals(0, checker.count()); + assertEquals(Order.INCREASING, checker.lastOrder()); + assertTrue(checker.isOrdered()); + assertEquals(0.0, checker.worstBackwardsStep()); + assertThrows(IllegalStateException.class, checker::lastTimestamp); + } + + @Test + void theFirstTimestampIsAlwaysAccepted() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + assertEquals(Order.INCREASING, checker.accept(-500.0)); + assertEquals(-500.0, checker.lastTimestamp()); + } + + @Test + void anOrderedStreamHasNoViolations() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + for (int i = 0; i < 20; i++) { + assertEquals(Order.INCREASING, checker.accept(i)); + } + assertTrue(checker.isOrdered()); + assertEquals(20, checker.count()); + } + + @Test + void reportsADuplicate() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.accept(10.0); + + assertEquals(Order.DUPLICATE, checker.accept(10.0)); + assertEquals(1, checker.duplicateCount()); + assertEquals(0, checker.backwardsCount()); + assertFalse(checker.isOrdered()); + } + + @Test + void reportsAStepBackwards() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.accept(10.0); + + assertEquals(Order.BACKWARDS, checker.accept(7.5)); + assertEquals(1, checker.backwardsCount()); + assertEquals(2.5, checker.worstBackwardsStep()); + } + + @Test + @DisplayName("the worst backwards step is the largest one, not the last one") + void keepsTheWorstBackwardsStep() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + checker.scan(new double[] {100.0, 60.0, 61.0, 59.0, 200.0, 199.0}); + + assertEquals(3, checker.backwardsCount()); + assertEquals(40.0, checker.worstBackwardsStep()); + } + + @Test + @DisplayName("the checker reports without reordering, so the last timestamp is the most recent one") + void doesNotReorderTheStream() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + checker.accept(100.0); + checker.accept(50.0); + + assertEquals(50.0, checker.lastTimestamp()); + assertEquals(Order.INCREASING, checker.accept(60.0), "the next sample is compared with the previous one, not with the maximum"); + } + + @Test + void scanReportsOneVerdictPerTimestamp() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + + Order[] verdicts = checker.scan(new double[] {1.0, 2.0, 2.0, 1.5, 3.0}); + + Assertions.assertArrayEquals(new Order[] {Order.INCREASING, Order.INCREASING, Order.DUPLICATE, Order.BACKWARDS, Order.INCREASING}, verdicts); + } + + @Test + void theVerdictKnowsWhetherItIsAViolation() { + assertFalse(Order.INCREASING.isViolation()); + assertTrue(Order.DUPLICATE.isViolation()); + assertTrue(Order.BACKWARDS.isViolation()); + } + + @Test + void resetRestoresTheInitialState() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.scan(new double[] {5.0, 4.0, 4.0}); + + checker.reset(); + + assertEquals(0, checker.count()); + assertEquals(0, checker.duplicateCount()); + assertEquals(0, checker.backwardsCount()); + assertEquals(0.0, checker.worstBackwardsStep()); + assertTrue(checker.isOrdered()); + assertThrows(IllegalStateException.class, checker::lastTimestamp); + } + + @Test + void toStringMentionsTheState() { + TimestampOrderChecker checker = new TimestampOrderChecker(); + checker.scan(new double[] {5.0, 4.0}); + + String text = checker.toString(); + + assertTrue(text.contains("TimestampOrderChecker")); + assertTrue(text.contains("backwards=1")); + } +} From e79b0f106477774020d4c5c2738f0854ff3d2444 Mon Sep 17 00:00:00 2001 From: Aman Mohamed Ali <69119173+spidervirus@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:01:34 +0400 Subject: [PATCH 11/19] fix(maths): ensure non-composite inputs are rejected in SmithNumber (#7756) - Reject numbers <= 3 as Smith numbers must be composite (greater than 3) - Fix bug where isSmithNumber(0) incorrectly returned true - Prevent integer overflow in trial division loop condition by using (long) i * i - Add comprehensive test cases covering non-composite inputs (negative numbers, 0, 1), primes, and valid Smith numbers --- src/main/java/com/thealgorithms/maths/SmithNumber.java | 5 ++--- src/test/java/com/thealgorithms/maths/SmithNumberTest.java | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/thealgorithms/maths/SmithNumber.java b/src/main/java/com/thealgorithms/maths/SmithNumber.java index c06e0023d9bb..41d7bebed257 100644 --- a/src/main/java/com/thealgorithms/maths/SmithNumber.java +++ b/src/main/java/com/thealgorithms/maths/SmithNumber.java @@ -18,10 +18,9 @@ private SmithNumber() { private static int primeFactorDigitSum(int n) { int sum = 0; - int num = n; // Factorize the number using trial division - for (int i = 2; i * i <= num; i++) { + for (int i = 2; (long) i * i <= n; i++) { while (n % i == 0) { // while i divides n sum += SumOfDigits.sumOfDigits(i); // add sum of digits of factor n /= i; // divide n by the factor @@ -43,7 +42,7 @@ private static int primeFactorDigitSum(int n) { * @return {@code true} if {@code number} is a Smith number, otherwise false */ public static boolean isSmithNumber(int number) { - if (PrimeCheck.isPrime(number)) { + if (number <= 3 || PrimeCheck.isPrime(number)) { return false; // Smith numbers must be composite } diff --git a/src/test/java/com/thealgorithms/maths/SmithNumberTest.java b/src/test/java/com/thealgorithms/maths/SmithNumberTest.java index 4e2ba0b88e33..b073cda880fb 100644 --- a/src/test/java/com/thealgorithms/maths/SmithNumberTest.java +++ b/src/test/java/com/thealgorithms/maths/SmithNumberTest.java @@ -9,13 +9,13 @@ class SmithNumberTest { @ParameterizedTest - @CsvSource({"4", "22", "121", "562", "985", "4937775"}) + @CsvSource({"4", "22", "27", "58", "85", "94", "121", "562", "985", "4937775"}) void positiveSmithNumbersTest(int n) { assertTrue(SmithNumber.isSmithNumber(n)); } @ParameterizedTest - @CsvSource({"2", "11", "100", "550", "999", "1234557"}) + @CsvSource({"-22", "-4", "-1", "0", "1", "2", "3", "5", "6", "8", "9", "10", "11", "100", "550", "999", "1234557"}) void negativeSmithNumbersTest(int n) { assertFalse(SmithNumber.isSmithNumber(n)); } From c1a7f8dd8ec6dbdc05eb260007dcbfdf9e8cc66d Mon Sep 17 00:00:00 2001 From: Bhumit Peswani Date: Thu, 19 Nov 2026 15:06:13 +0530 Subject: [PATCH 12/19] fix(heaps): prevent premature termination and return sorted array in MinPriorityQueue.heapSort (#7765) fix(heaps): prevent premature loop termination and return sorted elements in MinPriorityQueue.heapSort --- .../datastructures/heaps/MinPriorityQueue.java | 13 +++++++++---- .../heaps/MinPriorityQueueTest.java | 16 +++++++++++----- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java index a1360b14dc5a..dd636104c560 100644 --- a/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java +++ b/src/main/java/com/thealgorithms/datastructures/heaps/MinPriorityQueue.java @@ -100,12 +100,17 @@ public void print() { } /** - * Sorts the elements in the queue using heap sort. + * Sorts and returns the elements in the queue in ascending order using heap sort. + * + * @return an array containing all elements sorted in ascending order */ - public void heapSort() { - for (int i = 1; i <= this.size; i++) { - this.delete(); + public int[] heapSort() { + int initialSize = this.size; + int[] sorted = new int[initialSize]; + for (int i = 0; i < initialSize; i++) { + sorted[i] = this.delete(); } + return sorted; } /** diff --git a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java index 8f93bd630aa7..c493a141c61c 100644 --- a/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java +++ b/src/test/java/com/thealgorithms/datastructures/heaps/MinPriorityQueueTest.java @@ -55,13 +55,19 @@ void testHeapSort() { queue.insert(1); queue.insert(3); - // Delete all elements to sort the queue - int[] sortedArray = new int[5]; - for (int i = 0; i < 5; i++) { - sortedArray[i] = queue.delete(); - } + int[] sortedArray = queue.heapSort(); Assertions.assertArrayEquals(new int[] {1, 3, 5, 10, 15}, sortedArray, "The array should be sorted in ascending order."); + Assertions.assertTrue(queue.isEmpty(), "The queue should be empty after heap sort."); + } + + @Test + void testHeapSortEmptyQueue() { + MinPriorityQueue queue = new MinPriorityQueue(5); + int[] sortedArray = queue.heapSort(); + + Assertions.assertEquals(0, sortedArray.length, "Sorting an empty queue should return an empty array."); + Assertions.assertTrue(queue.isEmpty(), "The queue should remain empty."); } @Test From f4d6708297f86629a9e415070935b903ea8b1858 Mon Sep 17 00:00:00 2001 From: naveenkumar982 Date: Sat, 21 Nov 2026 00:44:01 +0530 Subject: [PATCH 13/19] Preserve the high bit in 32-bit Gray code conversion (#7761) Co-authored-by: Naveen Kumar <233027881+naveenkumar982@users.noreply.github.com> --- .../bitmanipulation/GrayCodeConversion.java | 8 ++++---- .../bitmanipulation/GrayCodeConversionTest.java | 12 ++++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java b/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java index 83cd30c7d50a..7266a5307798 100644 --- a/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java +++ b/src/main/java/com/thealgorithms/bitmanipulation/GrayCodeConversion.java @@ -2,7 +2,7 @@ /** * Gray code is a binary numeral system where two successive values differ in only one bit. - * This is a simple conversion between binary and Gray code. + * Each input and result is treated as a 32-bit pattern, including the sign bit. * Example: * 7 -> 0111 -> 0100 -> 4 * 4 -> 0100 -> 0111 -> 7 @@ -24,7 +24,7 @@ private GrayCodeConversion() { * @return The corresponding Gray code. */ public static int binaryToGray(int num) { - return num ^ (num >> 1); + return num ^ (num >>> 1); } /** @@ -35,8 +35,8 @@ public static int binaryToGray(int num) { */ public static int grayToBinary(int gray) { int binary = gray; - while (gray > 0) { - gray >>= 1; + while (gray != 0) { + gray >>>= 1; binary ^= gray; } return binary; diff --git a/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java b/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java index 1fe792028dca..69ac30755ee5 100644 --- a/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java +++ b/src/test/java/com/thealgorithms/bitmanipulation/GrayCodeConversionTest.java @@ -20,6 +20,18 @@ public void testGrayToBinary() { assertEquals(1, GrayCodeConversion.grayToBinary(1)); // 001 -> 001 } + @Test + public void testBinaryToGrayWithHighBitSet() { + assertEquals(0x80000000, GrayCodeConversion.binaryToGray(0xFFFFFFFF)); + assertEquals(0xC0000000, GrayCodeConversion.binaryToGray(0x80000000)); + } + + @Test + public void testGrayToBinaryWithHighBitSet() { + assertEquals(0xFFFFFFFF, GrayCodeConversion.grayToBinary(0x80000000)); + assertEquals(0x80000000, GrayCodeConversion.grayToBinary(0xC0000000)); + } + @Test public void testBinaryGrayCycle() { int binary = 9; // 1001 in binary From 9e216aa6d5eb94eafcc7056577a5e527f0555597 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:08:00 +0100 Subject: [PATCH 14/19] chore(deps): bump actions/setup-java from 6.2.0 to 6.3.0 in /.github/workflows (#7775) chore(deps): bump actions/setup-java in /.github/workflows Bumps [actions/setup-java](https://github.com/actions/setup-java) from 6.2.0 to 6.3.0. - [Release notes](https://github.com/actions/setup-java/releases) - [Commits](https://github.com/actions/setup-java/compare/v6.2.0...v6.3.0) --- updated-dependencies: - dependency-name: actions/setup-java dependency-version: 6.3.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/build.yml | 2 +- .github/workflows/codeql.yml | 2 +- .github/workflows/infer.yml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e83512b89972..ef45eef93278 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,7 +10,7 @@ jobs: steps: - uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.2.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 66d626f52876..29283197ba9b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -24,7 +24,7 @@ jobs: uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.2.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' diff --git a/.github/workflows/infer.yml b/.github/workflows/infer.yml index 0b7b1209e4a8..86e076f15d07 100644 --- a/.github/workflows/infer.yml +++ b/.github/workflows/infer.yml @@ -18,7 +18,7 @@ jobs: - uses: actions/checkout@v7 - name: Set up JDK - uses: actions/setup-java@v6.2.0 + uses: actions/setup-java@v6.3.0 with: java-version: 21 distribution: 'temurin' From 54d056dd35619d94e2d5c85c6d55c36bc3ca6841 Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Tue, 24 Nov 2026 13:43:36 +0530 Subject: [PATCH 15/19] fix: prevent digit position overflow in OctalToBinary for large octal inputs (#7776) * fix: use long digit position in OctalToBinary digitPosition grew as an int and overflowed for octal inputs with 5 or more digits, so convertOctalToBinary(10000) returned a negative value instead of 1000000000000. Making it a long keeps the position exact for the full range the method can represent. * test: cover OctalToBinary inputs with 5+ octal digits Fails on the current implementation because digitPosition overflowed int; passes with the long fix. --- .../com/thealgorithms/conversions/OctalToBinary.java | 2 +- .../thealgorithms/conversions/OctalToBinaryTest.java | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java index a66db97633b4..caa8ca95c9f1 100644 --- a/src/main/java/com/thealgorithms/conversions/OctalToBinary.java +++ b/src/main/java/com/thealgorithms/conversions/OctalToBinary.java @@ -37,7 +37,7 @@ private OctalToBinary() { */ public static long convertOctalToBinary(int octalNumber) { long binaryNumber = 0; - int digitPosition = 1; + long digitPosition = 1; while (octalNumber != 0) { int octalDigit = octalNumber % 10; diff --git a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java index 8e007151c301..eb440f647e44 100644 --- a/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java +++ b/src/test/java/com/thealgorithms/conversions/OctalToBinaryTest.java @@ -32,4 +32,14 @@ public void testConvertOctalToBinaryWithZeroPadding() { assertEquals(100001010, OctalToBinary.convertOctalToBinary(412)); assertEquals(101101110, OctalToBinary.convertOctalToBinary(556)); } + + @Test + public void testConvertOctalToBinaryLargeInput() { + // Regression: digit position overflowed int for octal inputs with 5+ digits + assertEquals(1000000000000L, OctalToBinary.convertOctalToBinary(10000)); + assertEquals(1000000000001L, OctalToBinary.convertOctalToBinary(10001)); + assertEquals(111111111111111L, OctalToBinary.convertOctalToBinary(77777)); + assertEquals(111111111111111111L, OctalToBinary.convertOctalToBinary(777777)); + assertEquals(1001001001001001001L, OctalToBinary.convertOctalToBinary(1111111)); + } } From 9870de2f545f4bcb162ffacca61009ca49b5b63e Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:10:52 +0530 Subject: [PATCH 16/19] fix: normalize Playfair key before building the matrix (#7779) * fix: normalize Playfair key before building the matrix encrypt() normalizes the plaintext (uppercase, J folded into I, non-letters stripped) but the constructor passed the raw key straight into the matrix builder. A lowercase key like "monarchy" or one containing J or punctuation produced a wrong matrix, so ciphertext was garbage and Z could never round-trip. Normalize the key the same way before building the matrix. * test: cover Playfair keys that are lowercase, contain J, or have non-letters Regression tests for the key-normalization fix: a lowercase key must behave like its uppercase form, a key containing J must still cover Z in the matrix, and punctuation or digits in the key must be ignored. --------- Co-authored-by: Oleksandr <19151554+alxkm@users.noreply.github.com> --- .../thealgorithms/ciphers/PlayfairCipher.java | 6 ++++- .../thealgorithms/ciphers/PlayfairTest.java | 26 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java index 76ceb6dbce31..3e29ea489dd8 100644 --- a/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/PlayfairCipher.java @@ -6,7 +6,11 @@ public class PlayfairCipher { private String key; public PlayfairCipher(String key) { - this.key = key; + // Normalize the key the same way the plaintext is normalized in encrypt(): + // uppercase, J folded into I, and non-letters removed. Without this a + // lowercase or mixed-case key, a key containing J, or a key with + // punctuation silently produces a wrong matrix. + this.key = key.toUpperCase().replace("J", "I").replaceAll("[^A-Z]", ""); generateMatrix(); } diff --git a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java index fa497e4682e8..2386aa735b7e 100644 --- a/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java +++ b/src/test/java/com/thealgorithms/ciphers/PlayfairTest.java @@ -34,4 +34,30 @@ public void testEncryptionAndDecryption() { assertEquals(plaintext, decryptedText); } + + @Test + public void testLowercaseKeyBehavesLikeUppercase() { + PlayfairCipher lowercase = new PlayfairCipher("monarchy"); + PlayfairCipher uppercase = new PlayfairCipher("MONARCHY"); + + assertEquals(uppercase.encrypt("HELLO"), lowercase.encrypt("HELLO")); + assertEquals("CFSUPM", lowercase.encrypt("HELLO")); + } + + @Test + public void testKeyContainingJStillCoversZ() { + PlayfairCipher playfairCipher = new PlayfairCipher("JUMP"); + + String decryptedText = playfairCipher.decrypt(playfairCipher.encrypt("ZOO")); + + assertEquals("ZOXO", decryptedText); + } + + @Test + public void testKeyWithNonLettersIsStripped() { + PlayfairCipher messy = new PlayfairCipher("Mon@rchy2026"); + PlayfairCipher clean = new PlayfairCipher("MONRCHY"); + + assertEquals(clean.encrypt("HELLO"), messy.encrypt("HELLO")); + } } From c86ec0a7e2bdac9d200c43f2afd9df3d3b94690b Mon Sep 17 00:00:00 2001 From: Aditya Kulkarni <213192267+Aditya2375@users.noreply.github.com> Date: Wed, 25 Nov 2026 00:17:51 +0530 Subject: [PATCH 17/19] fix: reject Hill cipher keys whose determinant is not coprime with 26 (#7780) * fix: reject Hill cipher keys whose determinant is not coprime with 26 The old validation only rejected a determinant of zero modulo 26. A key matrix is invertible mod 26 only when gcd(det, 26) = 1, so keys with determinant 2, 13, etc. passed validation but made encryption lossy: with key [[1,0],[0,2]] both "AA" and "AN" encrypt to "AA". Check coprimality instead, using floorMod so negative determinants are classified correctly. * test: cover Hill cipher keys with determinant 2, 13, or negative coprime Regression tests for the key-validation fix: keys with determinant 2 or 13 must be rejected even though they are not zero mod 26, and a key with determinant -1 (coprime) must still be accepted. --------- Co-authored-by: Oleksandr <19151554+alxkm@users.noreply.github.com> --- .../com/thealgorithms/ciphers/HillCipher.java | 16 ++++++++++---- .../thealgorithms/ciphers/HillCipherTest.java | 22 +++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/thealgorithms/ciphers/HillCipher.java b/src/main/java/com/thealgorithms/ciphers/HillCipher.java index 01b1aeb8bc6c..db86340aa3cf 100644 --- a/src/main/java/com/thealgorithms/ciphers/HillCipher.java +++ b/src/main/java/com/thealgorithms/ciphers/HillCipher.java @@ -68,14 +68,22 @@ public String decrypt(String message, int[][] inverseKeyMatrix) { return plainText.toString(); } - // Validates that the determinant of the key matrix is not zero modulo 26 + // Validates that the key matrix is invertible modulo 26, which requires the + // determinant to be coprime with 26. Checking only for a zero determinant is not + // enough: a determinant of 2 or 13 (or any other non-unit) passes that check but + // has no inverse, so encryption collapses distinct plaintexts onto the same + // ciphertext and decryption becomes impossible. private void validateDeterminant(int[][] keyMatrix, int n) { - int det = determinant(keyMatrix, n) % 26; - if (det == 0) { - throw new IllegalArgumentException("Invalid key matrix. Determinant is zero modulo 26."); + int det = Math.floorMod(determinant(keyMatrix, n), 26); + if (gcd(det, 26) != 1) { + throw new IllegalArgumentException("Invalid key matrix. Determinant must be coprime with 26 to be invertible modulo 26."); } } + private int gcd(int a, int b) { + return b == 0 ? a : gcd(b, a % b); + } + // Computes the determinant of a matrix recursively private int determinant(int[][] matrix, int n) { int det = 0; diff --git a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java index 8121b6177aa9..3f8b81c0d069 100644 --- a/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java +++ b/src/test/java/com/thealgorithms/ciphers/HillCipherTest.java @@ -1,6 +1,7 @@ package com.thealgorithms.ciphers; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; @@ -33,4 +34,25 @@ void hillCipherDecryptTest() { // then assertEquals("ACT", plainText); } + + @Test + void rejectsNonInvertibleKeyWithEvenDeterminant() { + // det = 2, gcd(2, 26) = 2: passes the old zero-check but has no inverse mod 26 + int[][] keyMatrix = {{1, 0}, {0, 2}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("AA", keyMatrix)); + } + + @Test + void rejectsNonInvertibleKeyWithDeterminantThirteen() { + // det = 13, gcd(13, 26) = 13: also not invertible mod 26 + int[][] keyMatrix = {{13, 0}, {0, 1}}; + assertThrows(IllegalArgumentException.class, () -> hillCipher.encrypt("BB", keyMatrix)); + } + + @Test + void acceptsKeyWithNegativeCoprimeDeterminant() { + // det = -1, coprime with 26: a valid key that a naive signed modulo would misclassify + int[][] keyMatrix = {{1, 2}, {1, 1}}; + assertEquals("XP", hillCipher.encrypt("HI", keyMatrix)); + } } From 15a4a9d36387782eb324416984b6e465d1c3f7cc Mon Sep 17 00:00:00 2001 From: Shreyansh Jain Date: Wed, 25 Nov 2026 00:24:38 +0530 Subject: [PATCH 18/19] fix(misc): prevent overflow when averaging the two middle values of a running median (#7781) fix(misc): prevent overflow when averaging the two middle values MedianOfRunningArrayInteger and MedianOfRunningArrayLong both compute (a + b) / 2, which overflows once the two middle values of the stream are large. For an Integer stream holding Integer.MAX_VALUE and Integer.MAX_VALUE - 2 the median came back as -2 instead of 2147483646; the Long version fails the same way near Long.MAX_VALUE. Sum in a long for the Integer case, and in a BigInteger for the Long case since there is no wider primitive. Add regression tests for both types at each end of their range. Co-authored-by: Oleksandr <19151554+alxkm@users.noreply.github.com> --- .../misc/MedianOfRunningArrayInteger.java | 4 ++- .../misc/MedianOfRunningArrayLong.java | 5 ++- .../misc/MedianOfRunningArrayTest.java | 36 +++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java index 7154ba073136..1a46077e25f5 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayInteger.java @@ -3,6 +3,8 @@ public final class MedianOfRunningArrayInteger extends MedianOfRunningArray { @Override public Integer calculateAverage(final Integer a, final Integer b) { - return (a + b) / 2; + // Widen to long so that summing values near Integer.MAX_VALUE does not overflow. + final long sum = (long) a + b; + return (int) (sum / 2); } } diff --git a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java index 1f138c6313fb..c7bf246d3523 100644 --- a/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java +++ b/src/main/java/com/thealgorithms/misc/MedianOfRunningArrayLong.java @@ -1,8 +1,11 @@ package com.thealgorithms.misc; +import java.math.BigInteger; + public final class MedianOfRunningArrayLong extends MedianOfRunningArray { @Override public Long calculateAverage(final Long a, final Long b) { - return (a + b) / 2L; + // a + b overflows a long near its bounds and there is no wider primitive to widen to. + return BigInteger.valueOf(a).add(BigInteger.valueOf(b)).divide(BigInteger.TWO).longValueExact(); } } diff --git a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java index c4a74af0ba8b..aa1d46c223d0 100644 --- a/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java +++ b/src/test/java/com/thealgorithms/misc/MedianOfRunningArrayTest.java @@ -190,6 +190,42 @@ public void testWithLongValues() { assertEquals(46116860244273878L, stream.getMedian()); } + @Test + public void testWithIntegerValuesNearMaxValue() { + var stream = new MedianOfRunningArrayInteger(); + stream.insert(Integer.MAX_VALUE); + assertEquals(Integer.MAX_VALUE, stream.getMedian()); + stream.insert(Integer.MAX_VALUE - 2); + assertEquals(Integer.MAX_VALUE - 1, stream.getMedian()); + stream.insert(2000000000); + assertEquals(Integer.MAX_VALUE - 2, stream.getMedian()); + } + + @Test + public void testWithIntegerValuesNearMinValue() { + var stream = new MedianOfRunningArrayInteger(); + stream.insert(Integer.MIN_VALUE); + stream.insert(Integer.MIN_VALUE + 2); + assertEquals(Integer.MIN_VALUE + 1, stream.getMedian()); + } + + @Test + public void testWithLongValuesNearMaxValue() { + var stream = new MedianOfRunningArrayLong(); + stream.insert(Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE, stream.getMedian()); + stream.insert(Long.MAX_VALUE - 2); + assertEquals(Long.MAX_VALUE - 1, stream.getMedian()); + } + + @Test + public void testWithLongValuesNearMinValue() { + var stream = new MedianOfRunningArrayLong(); + stream.insert(Long.MIN_VALUE); + stream.insert(Long.MIN_VALUE + 2); + assertEquals(Long.MIN_VALUE + 1, stream.getMedian()); + } + @Test public void testWithDoubleValues() { var stream = new MedianOfRunningArrayDouble(); From 3e421bc041a7e18402cdacc4c913fd6e5cc3c03d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:53:07 +0100 Subject: [PATCH 19/19] chore(deps): bump github/codeql-action from 4.39.3 to 4.39.4 in /.github/workflows (#7786) chore(deps): bump github/codeql-action in /.github/workflows Bumps [github/codeql-action](https://github.com/github/codeql-action) from 4.39.3 to 4.39.4. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v4.39.3...v4.39.4) --- updated-dependencies: - dependency-name: github/codeql-action dependency-version: 4.39.4 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 29283197ba9b..b745dc43c04b 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -30,7 +30,7 @@ jobs: distribution: 'temurin' - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.3 + uses: github/codeql-action/init@v4.39.4 with: languages: 'java-kotlin' @@ -38,7 +38,7 @@ jobs: run: mvn --batch-mode --update-snapshots verify - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.3 + uses: github/codeql-action/analyze@v4.39.4 with: category: "/language:java-kotlin" @@ -55,12 +55,12 @@ jobs: uses: actions/checkout@v7 - name: Initialize CodeQL - uses: github/codeql-action/init@v4.39.3 + uses: github/codeql-action/init@v4.39.4 with: languages: 'actions' - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v4.39.3 + uses: github/codeql-action/analyze@v4.39.4 with: category: "/language:actions" ...