minSubArrayLen
minSubArrayLen([2,3,1,2,4,3], 7) // 2 -> because [4,3] is the smallest subarrayfunction minSubArrayLen(arr, target){
let i = 0; // start
let j = 0; // end
let sum = 0;
let ret = Infinity;
while(i < arr.length){
if(sum < target && j < arr.length){
// Our solution isn't in the current target, so add up the current
// window and store it in the sum, and increment our window.
sum += arr[j];
j++
} else if( sum >= target){
// We have found our initial(and on going solution) in the current
// block, so therefore add it to the `ret` variable in order to
// keep track of the return value
// j - i would be the different of indexes
ret = Math.min(ret, j - i);
// We found the solution in the current window, so decrement and
// remove the index from the sum
// try to find the target sum in a subsequent window
sum -= arr[i];
i++
} else {
break;
}
}
// Infinitiy is the target because we'd need to compare the `positive` integer
// that needs to be GREATER than what we'd sumup
return ret === Infinity ? 0 : ret;
}Notes
Last updated