Skip to content

Commit c65cfd0

Browse files
committed
feat(slidingwindow): add SmallestSubarrayWithSum algorithm
1 parent bb6385e commit c65cfd0

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
/**
4+
* The Sliding Window algorithm is used to find the length of the smallest
5+
* contiguous subarray whose sum is greater than or equal to a given target.
6+
*
7+
* <p>Time Complexity: O(n)
8+
* <br>Space Complexity: O(1)
9+
*
10+
* <p>This class provides a static method to find the minimum length subarray
11+
* that satisfies the given sum condition.
12+
*
13+
* <p>Example:
14+
* <pre>
15+
* int[] nums = {2, 3, 1, 2, 4, 3};
16+
* int target = 7;
17+
* int result = SmallestSubarrayWithSum.findMinSubArrayLen(target, nums);
18+
* System.out.println(result); // Output: 2 (subarray [4,3])
19+
* </pre>
20+
*
21+
* @author Nihal
22+
*/
23+
public final class SmallestSubarrayWithSum {
24+
25+
// Prevent instantiation
26+
private SmallestSubarrayWithSum() {
27+
}
28+
29+
/**
30+
* Finds the minimal length of a contiguous subarray of which the sum ≥ target.
31+
*
32+
* @param target the target sum
33+
* @param nums the array of positive integers
34+
* @return the length of the smallest subarray with sum ≥ target,
35+
* or 0 if no such subarray exists
36+
*/
37+
public static int findMinSubArrayLen(int target, int[] nums) {
38+
int windowStart = 0;
39+
int windowSum = 0;
40+
int minLength = Integer.MAX_VALUE;
41+
42+
for (int windowEnd = 0; windowEnd < nums.length; windowEnd++) {
43+
windowSum += nums[windowEnd];
44+
45+
while (windowSum >= target) {
46+
minLength = Math.min(minLength, windowEnd - windowStart + 1);
47+
windowSum -= nums[windowStart];
48+
windowStart++;
49+
}
50+
}
51+
52+
return (minLength == Integer.MAX_VALUE) ? 0 : minLength;
53+
}
54+
}

0 commit comments

Comments
 (0)