Hi @Krishna_Tej_Chalamal
I see your point now. The author’s solution is different and can be a little bit confusing. The thing is, the first for loop is setting the end of the window. The inner while is just for sum the elements from the beginning of the window til the end (which is set by the for loop). Indeed, a given element can be processed more than once (and processed I mean, it can be used as part of the sum of the current window).
Saying that, the while loop will be running to sum the elements and as long the for loop do not reach the end, but the window interval (start - end) will be different every loop.
I give a try to solve this problem myself (I didn’t care for optimizations, but I think it is simpler than the author’s solution) and I used only a single while with the “if’s” and it worked fine. Take a look:
def min_subarray_sum(s, array):
min_len = float('Inf')
win_start = 0
win_end = 0
while win_start < len(array):
if sum(array[win_start:win_end]) >= s:
if len(array[win_start:win_end]) < min_len:
min_len = len(array[win_start:win_end])
win_start += 1
else:
if win_end < len(array):
win_end += 1
else:
win_start += 1
return min_len
Hope this helps!
Regards,
Artur Baruchi
Follow me on twitter for coding tips and technical content
twitter.com/abaruchi