Back and forth

1
2
3
4
count=0
for i in range(0,n):
   for j in range(i,0,-1):
        count=count+1

What is the time complexity of the above code snippet shown above?

O ( n ) O(n) O ( n 2 ) O(n^{2}) O ( n log n ) O(n\log n) O ( n 2 log n ) O(n^{2}\log n)

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Christopher Boo
May 15, 2016

For each i i in the first for loop, the second for loop will run count = count + 1 i i times. Since i i ranges from 0 0 to n n . The number of iterations are

1 + 2 + + n = n ( n + 1 ) 2 O ( n 2 ) 1+2+ \dots + n = \frac{n(n+1)}{2} \rightarrow O(n^2)

Rule of thumb : take only the one with the highest power, since they contribute more to the runtime, and remove any constants and coefficients.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...