Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package com.thealgorithms.slidingwindow;

/**
* Finds the length of the smallest contiguous subarray
* whose sum is greater than or equal to a given target.
*
* <p>Example:
* arr = [2, 3, 1, 2, 4, 3], target = 7
* Smallest subarray = [4, 3], length = 2
*
* <p>Time complexity: O(n)
* Space complexity: O(1)
*/
public final class SmallestSubarrayWithSum {

// Prevent instantiation
private SmallestSubarrayWithSum() {
}

/**
* Returns the minimal length of a contiguous subarray of which
* the sum ≥ target. If no such subarray exists, returns 0.
*
* @param arr the input array
* @param target the target sum
* @return the minimal subarray length, or 0 if not found
*/
public static int smallestSubarrayLen(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return 0;
}

int left = 0;
int sum = 0;
int 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;
}
}
Original file line number Diff line number Diff line change
@@ -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 {@link SmallestSubarrayWithSum}.
*/
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;
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));
}
}