Javatpoint Logo
Javatpoint Logo

Time Complexity

1. Time complexity of a simple loop when the loop variable is incremented or decremented by a constant amount:

Time Complexity

Here, i: It is a loop variable.

n: Number of times the loop is to be executed.

In above scenario, loop is executed 'n' times. Therefore, time complexity of this loop is O(n).

2. Time complexity of a loop when the loop variable is divided or multiplied by a constant amount:

Time Complexity

Here, i: It is a loop variable.

c: It is a constant.

n: Number of times the loop is to be executed.

In this case, Time complexity is O(logn).

3. Time complexity of a nested loop.

Time Complexity

Here, i: It is an outer loop variable.

j: It is an inner loop variable.

n: Number of times the loop is to be executed.

In this case, in each iteration of i, inner loop is executed 'n' times. The time complexity of a loop is equal to the number of times the innermost statement is to be executed.

Time complexity = O(n2).

4.Time complexity of an infinite loop

Infinite loop is executed "Infinite times". Therefore, there is no "algorithm time complexity" for an infinite loop.

5.Time complexities of different loops.

When there are more than one loop:

Time complexity of different loops is equal to the sum of the complexities of individual loop.

Therefore,

Time complexity = O(m)+O(n)


Help Others, Please Share

facebook twitter pinterest