Search code examples
time-complexityspace-complexity

n*n (not nested) for loop complexity


I know that the pattern for algorithm complexity when looking at nested loops is generally n^(m+1), where m is the loop nesting factor (loop within a loop).

But what about this simple case, where

for (i=0; i<n*n; i++) {
    ...
}

is the complexity O(n^2)?

Because the amount of executions is the same as it would be for a normal nested for loop.


Solution

  • Assuming the work done in each iteration of the for loop is O(1) then the complexity of the for loop is indeed O(n^2) since you iterate n^2 times. And yes, you assume correctly it would be of the same complexity as:

    for(i=0;i<n;i++) {
        for(j=0;j<n;j++) {
            ...
        }
    }