-1

I'm really having rough time understanding the time complexities of nested loops. So, please help me out in this code. The code is on sliding window with changing length:

def smallest_subarray_sum(s, arr):
    window_sum = 0
    min_length = math.inf
    window_start = 0
for window_end in range(0, len(arr)):
    window_sum += arr[window_end]  # add the next element
    # shrink the window as small as possible until the 'window_sum' is smaller than 's'
    while window_sum >= s:
        min_length = min(min_length, window_end - window_start + 1)
        window_sum -= arr[window_start]
        window_start += 1
if min_length == math.inf:
    return 0
return min_length

Also, please share some material to look into to understand big O for nested loops

VRM
  • 1

2 Answers2

0

Forget about there being a nested loop. There could be 10 nested loops; it wouldn't make a difference.

Ask yourself: How often is window_start increased? From that you can conclude how often the inner loop is executed and that solves the problem.

Note: It takes experience and training / practice to read code like this and figure out in your head what exactly it does. The easiest way is to write a program, then use a debugger, run the program, and see what happens. If you did that, say for an array of size 20, you would figure out easily what exactly is happening.

gnasher729
  • 29,996
  • 34
  • 54
0

Hint:

You cannot analyze this code in terms of two nested loops like in simpler cases, because the number of iterations of the inner loop varies depending on the data.

But you can solve this with a simple remark: as window_start grows by units, from 0, and will not exceed n:= len(arr), the total number of inner iterations cannot exceed n.