Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time complexity of nested for loop inside while loop

If there is a nested for loop inside while loop like this:

while(condition)
   for(i=0; i<size; i++)

the size in the for loop is increasing every time the for loop is being executed, starting at 1,2,...,n-1 and the while loop runs n-1 times.

That means that the time complexity is O(n^3)?

like image 756
Arthur Avatar asked Oct 18 '25 01:10

Arthur


1 Answers

If by every time the for loop is being executed you mean every time the while(condition) triggers a new run of the for loop, then the time complexity is .

That is, if you increment a counter inside the inner for loop, it will be incremented n * (n - 1) / 2 = n choose 2 times. But because constant factors and lower order terms are omitted in big O notation, we can just write .

For illustration, consider this Python 2.7 implementation (I converted the outer while loop + size increment into a for loop):

n = 10
counter = 0

for size in range(1, n):
    for i in range(0, size):
        counter += 1
        print i,
    print
print

print "counter =", counter
print "n choose 2 =", n * (n - 1) / 2

Output:

0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8

counter = 45
n choose 2 = 45

Try running it with different values of n to see that the formula holds true.

like image 172
runcoderun Avatar answered Oct 21 '25 22:10

runcoderun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!