Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do multiple loops have same complexity as nested loops?

This for loop has a complexity of O(n)

for ($i=0; $i < $arrCount - 1; $i++) { }

And this 2 nested for loops have a complexity of O(n^2)

for ($i=0; $i < $arrCount; $i++) { 
  for ($j=0; $j < $arrCount; $i++) { 
  }
}

But what if I did 2 for loops inside a function and they just folowed each other, no nesting

for ($i=0; $i < $arrCount; $i++) { 
}
for ($i=0; $i < $arrCount; $i++) { 
}

Would the function still be executed in O(n) ?

like image 731
Alucard Avatar asked Aug 30 '15 22:08

Alucard


People also ask

What is the complexity of nested for loop?

The time complexity of nested loops is equal to the number of times the innermost statement is executed.

What is the time complexity of 3 nested for loop?

+n iterations n*(n+1)/2 which is O(n2) . for(i = 1; i < n; i++) { for(j = i+1; j <= n; j++) { for(k = i; k <= j; k++) { // Do something here... } } }

Are nested for loops faster?

HOWEVER, the conclusion is CONSISTENT: The nested loop is much FASTER. When the iteration time is 100^5, the difference is significant: 321.49 vs 210.05. There is about 1.53-time gap between them. Generally, we don't face this kind of long iteration, I'm just curious to know reason of the anomalistic situation.

What is the difference between a loop and a nested loop?

A nested loop is just a loop that's been put in another loop.


1 Answers

Yes.

Nested loops means that the outer loop will execute the inner one completely for each iteration (of the outer). This means O(n^2) in your case, because for each i from 0 to n we do n operations.

i = 0 => inner loop runs n iterations
i = 1 => inner loop runs n iterations
...
i = n - 1 => inner loop runs n iterations

n iterations n times means n^2 total iterations, so O(n^2).

Your 2 loops without nesting will each iterate n times, for a total of 2n times. Big-oh ignores constants, so 2n = O(n).

Since they are not nested, the number of times each one runs will not depend on the other. So you add the number of iterations, not multiply them.

like image 163
IVlad Avatar answered Oct 21 '22 05:10

IVlad