Let us discuss some important examples of 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 .
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).
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
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’.
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.
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
LOOP_CMPL | 20 |
|
2:43 | |
NESTED_CMPL | 20 |
|
1:10 | |
NESTED_CMPL2 | 30 |
|
1:25 | |
CHOOSE4 | 50 |
|
0:57 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
WHILE_CMPL | 50 |
|
1:31 | |
NESTED_CMPL3 | 80 |
|
3:56 | |
LOOP_CMPL2 | 80 |
|
2:43 | |
GCD_CMPL | 150 |
|
4:13 |
Problem | Score | Companies | Time | Status |
---|---|---|---|---|
AMORTIZED1 | 100 |
|
3:03 |