Let us discuss some important examples of time complexity.
Example 1: The following is the program for finding the highest power less than 2. Find its Time complexity.
Time Complexity: The time complexity of the above program is O(log2n) . This is because at every step we divide n by 2 .
Example 2: The following is the program for finding all the subsets of a given set. Find its Time complexity.
Time Complexity: As can be seen , the outer loop runs O(2^n) times, and the inner loop runs O(n) times.
Therefore the total time complexity is the multiplication of both i.e. O(2^n * n).
Example 3: Let’s take the example of a fibonacci number. The following program finds the nth fibonacci number. What is its time complexity?
The derivation of the time complexity is slightly non trivial , so you can skip it if you want.
The characteristic equation of the equation ( F(n) = F(n-1) + F(n-2) ) would be x^2 - x -1 =0
Solving the above equation we would get 2 roots.
x= ( 1 + 5 )/2 and x= ( 1 - 5 )/2
As we know the solution of a linear recursive function is given as
F(n) = (1n + 2n )
Using the above fact
- F(n) = ( ( 1 + 5 )/2 ) ^n + ( ( 1 - 5 )/2 ) ^n
- T(n) = O ( ( ( 1 + 5 )/2 ) ^n) + O( ( ( 1 - 5 )/2 ) ^n)
- T(n) = O ( ( ( 1 + 5 )/2 ) ^n)
- T(n) = O ( 1.6180 ) ^n
But is this the best time complexity we can achieve? No , of course not. We can simply use dynamic programming to memoize the above program and bring down the complexity to linear.
The time complexity of the above program would be linear i.e. O(n).
As there are only ‘n’ distinct states.
We can further reduce the time complexity to O(logn) by using ‘Matrix Exponentiation’.
Example 4: This is a very commonly asked question in the interview. What is the time complexity of the below program?
Even though the time complexity of the above algorithm appears to be O(n*n) , in reality it is actually O (nlogn). You can try to derive it by yourself.
The same principle is used in many famous algorithms like sieve.