How do I find the time complexity (Big O) of while loop?

The first code sample is pretty much a classis for loop. Its complexity is O(n^2). This is because the inner loop has a complexity O(n) and it is run n times.

The second one is a bit more difficult, untill you see that is equivalent to a non nested loop (ignoring the complexity of the checks)

int result = 0;
int i = 0;
while (i < n){
    result += arr[i];
    i += 1;
}
printf("%d\n", result);

meaning its complexity is O(n)

The best approach to calculating time complexity is trying to actually understand how the algorithm works and counting the operations. In the second example, the inner loop never runs untill the outer loop is at its last iteration. And since they even execute the same code, the whole thing can be reduced to one loop.

Another good example is this:

for(i=0;i<n;i++){
    for(j=i;j<n;i++){
        //do something
    }
}

Let’s count the operations: 1 + 2 + 3 + 4 + … + n. This comes down to n*n/2 leading to O(n^2)

Leave a Comment