Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Big-O of a nested loop, where number of iterations in the inner loop is determined by the current iteration of the outer loop?

People also ask

What is the big O time complexity when you have a loop within a 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 total complexity for the two loops is O(N2).

What is the big O time complexity of the following for var i 0 in i ++)?

for(var i = 0; i < length; i++) { //has O(n) time complexity for(var j = 0; j < length; j++) { //has O(n^2) time complexity // More loops? }} Other examples of quadratic time complexity include bubble sort, selection sort, and insertion sort.

How do you find the total number of iterations in a nested loop?

The number of iterations for the nested for loops is N=N1×N2.

How do you find the complexity of a nested loop?

As the nested loops always run to completion and there is a constant amount of code within the inner loop, the time complexity can be determined by taking the sum of the number of inner loop iterations in the worst case.


Yep, it's still O(n^2), it has a smaller constant factor, but that doesn't affect O notation.


Yes. Recall the definition of Big-O: O(f(n)) by definition says that the run time T(n)kf(n) for some constant k. In this case, the number of steps will be (n-1)+(n-2)+...+0, which rearranges to the sum of 0 to n-1; this is

T(n)=(n-1)((n-1)+1)/2.

Rearrange that and you can see that T(n) will always be ≤ 1/2(n²); by the definition, thus T(n) = O(n²).


It's N squared if you ignore the System.out.println. If you assume that the time taken by that will be linear in its output (which it may well not be, of course), I suspect you end up with O ( (N^2) * log N).

I mention this not to be picky, but just to point out that you don't just need to take the obvious loops into account when working out complexity - you need to look at the complexity of what you call as well.


Yes, it would be N squared. The actual number of steps would the sum of 1 to N, which is .5*(N - 1)^2, if I'm not mistaken. Big O only takes into account the highest exponant and no constants, and thus, this is still N squared.