Practice Questions on Time Complexity Analysis in C++

C++Server Side ProgrammingProgramming

Time complexity of any algorithm is the time taken by the algorithm to complete. It is an important matrix to show the efficiency of the algorithm and for comparative analysis. We tend to reduce the time complexity of algorithm that makes it more effective.

Find the time complexity of the following code snippets

for(i= n ; i > 0; i++){
   cout<<i;
   i++;
}

The loop has maximum value n but the i will be incremented twice in the for loop which will make the time take half.

Time complexity: O(n/2)

for(i= n ; i > 0; i++){
   for(j = 0; j<n;j++){
      cout<<i;
   }
}

Here it is evidant that for each iteation of outer loop, inner loop will be executed n times.

So, Time Complexity: O(n2) or O(N*N)

int i = N;
while(i){
   cout<<i;
   i = i/2 ;
}

Here, after every iteration value of i will be divided by 2. So, time complexity: O(log(n))

if(i > j ){
   j>23 ? cout<<j : cout<<i;
}

There are two conditional statements in the code. Each conditional statement has time complexity = O(1).

Time complexity : O(2)

for(i= n ; i > 0; i++){
   for(j = 0; j<n;j*2){
      cout<<i;
   }
}

Here, we have nested loops and the inner loop has multiplication as increment operator. So, the complexity of the inner loop will be of the order log(n). And have of outer will be of the order n. So,

Time complexity: O(nlog(n))

raja
Published on 04-Feb-2020 07:42:38
Advertisements