Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of an iteration through all possible sequences of an array

An algorithm that goes through all possible sequences of indexes inside an array.

Time complexity of a single loop and is linear and two nested loops is quadratic O(n^2). But what if another loop is nested and goes through all indexes separated between these two indexes? Does the time complexity rise to cubic O(n^3)? When N becomes very large it doesn't seem that there are enough iterations to consider the complexity cubic yet it seems to big to be quadratic O(n^2)

Here is the algorithm considering N = array length

for(int i=0; i < N; i++)
{
    for(int j=i; j < N; j++)
    {
        for(int start=i; start <= j; start++)
        {
          //statement
        }
    }
}

Here is a simple visual of the iterations when N=7(which goes on until i=7):

enter image description here enter image description here

And so on..

Should we consider the time complexity here quadratic, cubic or as a different size complexity?

like image 209
danny bee Avatar asked May 17 '19 13:05

danny bee


People also ask

What is the time complexity of iterating an array to print all the values?

For iterating through the array list, the time complexity will be O(n). n will be the size of the list. for getting the value using get(), it will be O(1), random access is possible in array list using index. And for adding the values using add(), the value is getting added at the last, so it will be O(1).

What will be the time complexity for printing all the elements of an linear array of size n?

If we implement (Algorithm A) going through all the elements in an array, it will take a running time of O(n) .

What is the time complexity of 4 for loops?

The best case time complexity is constant, O(1) . Best case will happen when the first and second element of the grid A are equal. The worst case complexity is O(n^4) . Worst case will happen when all the elements of the grid A are unique.

What is the time complexity of 3 for loops?

O(nc): Time complexity of nested loops is equal to the number of times the innermost statement is executed. An algorithm with three-nested loops will have O(n3)


1 Answers

For the basic

for (int i = 0; i < N; i++) {
    for (int j = i; j < N; j++) {
        // something
    }
}

we execute something n * (n+1) / 2 times => O(n^2). As to why: it is the simplified form of
sum (sum 1 from y=x to n) from x=1 to n.

For your new case we have a similar formula:
sum (sum (sum 1 from z=x to y) from y=x to n) from x=1 to n. The result is n * (n + 1) * (n + 2) / 6 => O(n^3) => the time complexity is cubic.

The 1 in both formulas is where you enter the cost of something. This is in particular where you extend the formula further.

Note that all the indices may be off by one, I did not pay particular attention to < vs <=, etc.

like image 159
luk2302 Avatar answered Sep 27 '22 20:09

luk2302