Hi @Amit_Adiraju_Narasim !
Thanks for contacting the Educative team.
In this case, the bottleneck of the algorithm is the sum += 1
line. It is O(1) by itself, of course, so the question is: how often is that line executed? The time complexity of the inner loop is dependent on the outer loop because of the variable var
. For the first iteration of the outer loop, the inner loop code (sum += 1
) executed 1(2^0=1) time, for the second iteration, it executed 2(2^1=2) times, and for 3rd iteration, it executed 4(2^2=4) times and so on. Here its complexity is totally dependent on the outer loop.
We can find the time complexity of the algorithm by finding out the number of times a code (common to both loops i.e, in this case (sum += 1
)) is executed. So, the sum += 1
line is executed 1 + 2 + 4 + … + 2k = 2 × ( 2k ) - 1 times. O(2 × ( 2k ) - 1) = O( 2k ) = O(n) .
Similarly, for the following code, the bottleneck of the algorithm (challenge 4) is the sum += 1
line. Here, we loop over range(1, n, 2)
, and this line is executed n (here 5) times for each iteration of the outer loop. But that’s O((n - 1)/2) = O(n) independent of the value of var
. So we get O(n) + O(n) + … + O(n), with one term per iteration of the outer loop, which we established is O(log n), hence O(log n) × O(n) = O(n log n).
while var < n:
print(pie)
for j in range(1, n, 2):
sum += 1
var *= 3
print(sum)
I hope it helps. Happy Learning