Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

time complexity question how is it solved

Can someone please explain how this is O(n^2) I am not sure how they got this answer

for(i = 0; i < n; i++){
   if (a[i] > b[i]){
      print(a[i]-b[i]);
   }
   else{
      print(b[i]-a[i]);
   }
}
for(i = 0; i < n; i++){
   for(j = 0; i < n; j++){
      c[i][j] = 0;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Time complexity can be calculated by calculating the order of iterations.
in the code that you have shared

//1
    for(i = 0; i < n; i++){ // o(n)  
       if (a[i] > b[i]){
          print(a[i]-b[i]);
       }
       else{
          print(b[i]-a[i]);
       }
    }
//2
    for(i = 0; i < n; i++){   // o(n) 
       for(j = 0; i < n; j++){ //  o(n)
          c[i][j] = 0;
        }
    }

Now when

  1. i = 0 , the inner for loop will run n times

  2. i =1 ,the inner for loop will run n times.

  3. i = n-1, the inner for loop will run n times

Therefore inner for loop will run n times for each value of i ( from 0 to n-1 ). therefore the time complexity is o(n*n)

The total time complexity is o(n^2) ( from 2 for loop ) + o(n) ( from 1st for loop )
since o(n^2) dominates o(n) , we consider only the highest power of n.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading