educative.io

My Solution doesn't work even though it looks identical to the provided solution

Can any one tell me why this solution doesn’t work? Give out all result = 0; when I console.log start to the screen, it starts to loop through the array and then when it gets to the last element it run back to the first element even though I have condition for the loop as end < arr.length. weird!
const smallest_subarray_with_given_sum = function(s, arr) {
let start = 0;
let sum = 0;
let minLength = Infinity;
for (let end = 0; end < arr.length; end ++ ) {
console.log({end})
sum += arr[end];
console.log({sum})
while (sum >= s) {
//get min
minLength = Math.min(minLength, end - start + 1);
console.log({minLength})
sum -= arr[start];
console.log({sumDe: sum})
start+=1;
}
}
return minLength = Infinity ? 0 : minLength;
};

There is a syntax error in your last line, “return minLength = Infinity ? 0 : minLength;” that’s why you are unable to find the solution.

Single equal is just used as an assignment operator. You can use double or triple equal as a comparison operator here.
“return minLength == Infinity ? 0 : minLength;”

1 Like