diff --git a/src/main/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSum.java b/src/main/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSum.java new file mode 100644 index 000000000000..e6ecbca17f5e --- /dev/null +++ b/src/main/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSum.java @@ -0,0 +1,18 @@ +package com.thealgorithms.slidingwindow; + +public class SmallestSubarrayWithSum { + + public static int smallestSubarrayLen(int[] arr, int target) { + if (arr == null || arr.length == 0) return 0; + int left = 0, sum = 0, minLen = Integer.MAX_VALUE; + + for (int right = 0; right < arr.length; right++) { + sum += arr[right]; + while (sum >= target) { + minLen = Math.min(minLen, right - left + 1); + sum -= arr[left++]; + } + } + return minLen == Integer.MAX_VALUE ? 0 : minLen; + } +} diff --git a/src/test/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSumTest.java b/src/test/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSumTest.java new file mode 100644 index 000000000000..01c2427455de --- /dev/null +++ b/src/test/java/com/thealgorithms/slidingwindow/SmallestSubarrayWithSumTest.java @@ -0,0 +1,50 @@ +package com.thealgorithms.slidingwindow; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +/** + * Unit tests for SmallestSubarrayWithSum algorithm + */ +public class SmallestSubarrayWithSumTest { + + @Test + public void testBasicCase() { + int[] arr = {2, 3, 1, 2, 4, 3}; + int target = 7; + int expected = 2; // subarray [4,3] + assertEquals(expected, SmallestSubarrayWithSum.smallestSubarrayLen(arr, target)); + } + + @Test + public void testNoValidSubarray() { + int[] arr = {1, 1, 1, 1}; + int target = 10; + int expected = 0; // no subarray reaches target + assertEquals(expected, SmallestSubarrayWithSum.smallestSubarrayLen(arr, target)); + } + + @Test + public void testSingleElement() { + int[] arr = {5}; + int target = 5; + int expected = 1; + assertEquals(expected, SmallestSubarrayWithSum.smallestSubarrayLen(arr, target)); + } + + @Test + public void testAllElementsSame() { + int[] arr = {2, 2, 2, 2, 2}; + int target = 6; + int expected = 3; + assertEquals(expected, SmallestSubarrayWithSum.smallestSubarrayLen(arr, target)); + } + + @Test + public void testLargeInput() { + int[] arr = {1, 2, 3, 4, 5, 6}; + int target = 11; + int expected = 2; // subarray [5,6] + assertEquals(expected, SmallestSubarrayWithSum.smallestSubarrayLen(arr, target)); + } +}