I’m thinking about a an extreme edge case scenario where somehow there is a subarray that has the given sum and that sub array has a length of Integer.MAX_VALUE. Is that technically possible? In that case, we wouldn’t want to return 0 we would want to return that value, the Integer.MAX_VALUE. My solution has a boolean flag that accounts for that. But maybe I’m imagining an impossible scenario.
public static int smallestSubArray(int s, int[] numbers) {
int windowStart = 0;
int windowEnd = 0;
int smallestLength = Integer.MAX_VALUE;
boolean matchFound = false;
int currentSum = numbers[0];
while (windowStart <= numbers.length - 1) {
int subArraySize = (windowEnd - windowStart) + 1;
if (currentSum >= s) {
matchFound = true;
smallestLength = Math.min(smallestLength, subArraySize);
if (smallestLength == 1) { break; }
currentSum -= numbers[windowStart];
windowStart++;
} else {
windowEnd++;
currentSum += numbers[windowEnd];
}
}
return !matchFound ? 0 : smallestLength;
}