educative.io

Why while loop i used if condition to shrink window?

Hello - In Smallest Subarray with a given sum (easy) example, why while loop is used instead of if condition (similar to earlier examples) ? Wouldn’t it be always the last number which is causing the sum to exceed the desired sum?Could you please explain?

If recently added number is very big and number you subtracted is small, you can subtract a few more numbers and you can get smaller window.
For example array = [1,1,2,1,2,3,1,2,8] , sum = 10
when you add 8 , you will remove 2,3,2,3,1 to narrow the window just for [2,8]

1 Like

Hi Yalcin_Cakmak - Oh okay… thanks for clear cut explanation !