Run Time Of Nested While Loop That Doesn't Reset

LeoC :

Would the following code be O(n^2) or O(n)?

int i=0, j=0;
while (i < n) {
  while (j < n) {
    j++;
  }
  i++;
}

Since the inner while loop only runs once from 0 to n I would imagine it's equivalent to having two separate while loops thus the total run-time would be O(2n).

satyesht :

It is O(n) in this particular pieces of code . Eg If n=10 for i=0 inner loop executes from j=0 to j=9(10 times ) and for i = 1 to 9 inner loop exeutes 0 times , (since j(10) >n(10) will never become true), So total time = 10 times outer + 10 times inner = 20= 2n Hence time complexity is O(n)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=97320&siteId=1