简体   繁体   中英

Time complexity for 2 nested loops

If I'm taking input through 2 nested For-loops like this

cin>>x;

for(i=0;i<x;i++)
{
   cin>>y;

for(j=0;j<y;j++)

}

The complexity of the Outer loop is O(X) but I'm confused about the Time complexity of the inner loop as the Y is variable.

The complexity of the outer loop is not O(x) , because the time it takes to run the outer loop depends on the value of y entered.

Let's say we have a sequence y1,y2,...,yn of inputs for y. Then the first loop would take y1 operations and the second iteration would take y2 operations and so on for each of the x iterations.

Now let Y be the max of this sequence of inputs, then each iteration of the outer loop would take at most Y operations. So we have that for x iterations each taking at most Y operations we get O(xY).

It is possible to specify further to a possibly smaller class of functions but it's important to remember that if f < g then O(f) is contained in O(g) . And that when we say a function is O(f) we just mean it is inside the class O(f) .

Considering in this case the input is not determined using the max would be a worst case scenario.

Also it would be more accurate if the input was outside all the loops as input isn't a constant operation most of the time. (This is trivial though, just have the y be input from a file or something and then use that to make an array.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM