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,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;
}
}
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 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));
}
}
Loading