educative.io

Why do we need two for loops?

why do we have to use two for loops? it can be done with a single forloop and a while loop and no need of collection as well

def find_subarrays(arr, target):
result = []
for right in range(len(arr)):
    product = 1
    currentset = []
    while right <= len(arr)-1:
        product *=arr[right]
        if product < target:
            currentset.append(arr[right])
            result.append(list(currentset))
            right +=1
        else:
            break
return result

Hi @Prasanth_Ganesan

The approach you have followed is also a valid one, both these codes output the same result and have the same Time Complexity as both examples are performed using a nested loop. So either code could be used.

1 Like