Min subarray length algorithm in JavaScript
Given an array of positive intergers and a positive integer target, return the length of the shortest possible contiguos sub-array with a sum greater than or equal to the target.
function minSubArrayLen(items, targ) {
let left = 0;
let right = 0;
let currSum = 0;
let minLen = Infinity;
while (left < items.length) {
if (currSum < targ) {
if (right === items.length) {
break;
}
currSum += items[right];
right++;
} else {
minLen = Math.min(minLen, right - left);
currSum -= items[left];
left++;
}
}
return minLen === Infinity ? 0 : minLen;
}
This solution has $O(n)$ time complexity because we iterate the main array once, and $O(1)$ space complexity because we only store a fixed set of variables while moving through the main array.