Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O for 3 nested loops

Another Big O notation question...What is the Big O for the folling code:

     for (int i = n; i > 0; i = i / 2){
        for (int j = 0; j < n; j++){
           for (int k = 0; k < n; k++){
              count++;
           }
        }
     }

My Thoughts: So breaking it down, I think the outside loop is O(log2(n)), then each of the inner loops is O(n) which would result in O(n^2 * log2(n)) Question #1 is that correct?

Question #2: when combining nested loops is it always just as simple as mulitply the Big O of each loop?

like image 780
Kailua Bum Avatar asked Jan 24 '13 21:01

Kailua Bum


1 Answers

When loop counters do not depend on one another, it's always possible to work from the inside outward.

The innermost loop always takes time O(n), because it loops n times regardless of the values of j and i.

When the second loop runs, it runs for O(n) iterations, on each iteration doing O(n) work to run the innermost loop. This takes time O(n2).

Finally, when the outer loop runs, it does O(n2) work per iteration. It also runs for O(log n) iterations, since it runs equal to the number of times you have to divide n by two before you reach 1. Consequently, the total work is O(n2 log n).

In general, you cannot just multiply loops together, since their bounds might depend on one another. In this case, though, since there is no dependency, the runtimes can just be multiplied. Hopefully the above reasoning sheds some light on why this is - it's because if you work from the inside out thinking about how much work each loop does and how many times it does it, the runtimes end up getting multiplied together.

Hope this helps!

like image 85
templatetypedef Avatar answered Oct 01 '22 22:10

templatetypedef