What is the time complexity of while loops?

When you gotta do something n times, you have to do it n times. You can use a for loop, a while loop or whatever that your programming language (or pseudo code!) offers. Crudely, big O notation comments on the amount of work you have to do, and doesn’t care about how you do it (somewhat less crudely, it comments on how the amount of work that needs to be done grows with the growing input).

Keep reading for the details.


I think you are confusing things here. for and while are programming language constructs to express operations that are to be repeated.

Algorithm analysis is agnostic of the language of implementation, and doesn’t care about the actual constructs you use while expressing the algorithm.

Consider following:

1. Input n
2. Do OperationX n times

The Big O notation machinery helps you in commenting on the complexity of the above operation. This helps in many cases. For example, it can help you in comparing the runtime of the operation above with the following:

1. Input n
2. Input m
3. Repeat m OperationX n times.

The Big O notation will tell you that the former is O(n) and the latter is O(m * n) (assuming OperationX takes a constant time).

You can write the code using the loop construct of your choice, it doesn’t matter.

for(int i = 0; i < n; i++) {
    operationX;
}

Is the first operation, and

i = j = 0;
while(i < n) {
    j = 0;
    while(j < m) {
      operationX;
      j++;
    }
    i++;
}

the second. The big O notation doesn’t really care if the for and while was switched.


A[n] = some array of length n;
for(x = 0;x != A[i];i++) {

}

Is a for re-write of your question with the same complexity (O(n)).

Leave a Comment