Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Big O for a nested series of for loops

I've got a question about calculating Big O running times for a series of loops, that are nested in an outer for loop.

For example:


for (50,000 times)
{
    for (n times)
    {
        //Do something
    }
    for (n-2 times)
    {
        //Do something
    }
    for (n times)
    {
        //Do something
    }
    for (n-2 times)
    {
        //Do something
    }
}

The outer loop is a constant, so I think that is ignored. Is it then as easy as doing the following calculation?

N + N-2 + N + N-2

2N + 2(N-2)

4N - 4

O(4N - 4)

O(4N) - after removing the -4 constant

Is this correct?

Thanks.

like image 889
Tom W Avatar asked Nov 28 '10 00:11

Tom W


People also ask

What is the big O complexity of a nested loop?

The outer loop executes N times. Every time the outer loop executes, the inner loop executes M times. As a result, the statements in the inner loop execute a total of N * M times. Thus, the complexity is O(N * M).

How do you calculate big O for nested loops?

You can calculate big O like this: Any number of nested loops will add an additional power of 1 to n. So, if we have three nested loops, the big O would be O(n^3). For any number of loops, the big O is O(n^(number of loops)).

What is the big O of a triple nested loop?

It will be 0(n^3) complexity as there are 3 loops with 0(n) complexity. As your number of loop increases, the time complexity of your method keeps on multiplying. So you have n loops in your program, then time complexity of your program will be 0(n^n).

What is the time complexity of multiple loops?

The Time Complexity of a loop is considered as O(n) if the loop variables are incremented/decremented by a constant amount. For example following functions have O(n) time complexity.


1 Answers

This is O(n)

(you are only interested in what is the "largest" part of the equation, and you strip the constant).

If you had a loop i from 1..n and another loop inside j from i..n, it would be O(n^2).

like image 143
Thorbjørn Ravn Andersen Avatar answered Sep 29 '22 02:09

Thorbjørn Ravn Andersen