in Algorithms
463 views
0 votes
0 votes
for(i=0;i<n;i++)

   for(j=0;j<i;j++)

      for(k=0;k<j;k++)

 

what is the time complexity of above psudo code?

explain.
in Algorithms
463 views

2 Comments

edited by
It is

O( n^3 ).
0
0

first loop is executed for n times i=0,1....n-1

second loop is called for every value of i, so second loop runs for 0 iterations then 1 then 2, ...... and finally n-1

so in total 1+2+3+....+n-1 = (n-1)(n)/2 times

third loop runs for every value of j

so first when j=1, third loop runs once

when j=2, third loop runs for k=0 and k=1 so twice

And similarly when j= n-1 total n-1 loops

1+(1+2)+(1+2+3)+(1+2+3+4)+.....+(1+2+3+4....n-1)

=(n-1)(1) +(n-2)(2)+ (n-3)(3)+.......(1)(n-1)

=(n-1)(1) +(n-2)(2)+ (n-3)(3)+.......(n-(n-1))(n-1)

=[n+2n+3n+4n+5n+6n+.......(n-1)n]-[ 12+22+32+42+....(n-1)2]

=[n(1+2+3+4+5+6+.......(n-1)]-[ 12+22+32+42+....(n-1)2]

=n(n-1)(n)/2 - [12+22+32+42+....(n-1)2]

=[n(n-1)(n)/2] - [(n-1)*n*(2n-2+1)/6]

=(n3+n)/6

=$\Theta$(n3)

 

4
4

1 Answer

2 votes
2 votes
I think the answer is O(n^3)

2 Comments

Yes it is O(n^3)
0
0
Can you elobrate?
0
0