I am trying to find complexity of Fibonacci series using a recursion tree and concluded height of tree = O(n)
worst case, cost of each level = cn
, hence complexity = n*n=n^2
How come it is O(2^n)
?
I am trying to find complexity of Fibonacci series using a recursion tree and concluded height of tree = O(n)
worst case, cost of each level = cn
, hence complexity = n*n=n^2
How come it is O(2^n)
?
Look at it like this. Assume the complexity of calculating
F(k)
, thekth
Fibonacci number, by recursion is at most2^k
fork <= n
. This is our induction hypothesis. Then the complexity of calculatingF(n + 1)
by recursion iswhich has complexity
2^n + 2^(n - 1)
. Note thatWe have shown by induction that the claim that calculating
F(k)
by recursion is at most2^k
is correct.t(n)=t(n-1)+t(n-2) which can be solved through tree method:
similarly for the last level . . 2^n
it will make total time complexity=>2+4+8+.....2^n after solving the above gp we will get time complexity as O(2^n)
The complexity of recursive Fibonacci series is 2^n:
This will be the Recurrence Relations for recursive Fibonacci
Now on solving this relation using substitution method (substituting value of T(n-1) and T(n-2))
Again substituting values of above term we will get
After solving it completely, we get
This implies that maximum no of recursive calls at any level will be at most 2^n.
And for all the recursive calls in equation 3 is ϴ(1) so time complexity will be
2^n* ϴ(1)=2^n
The complexity of a naive recursive fibonacci is indeed 2ⁿ.
In each step you call
T
twice, thus will provide eventual asymptotic barrier of:T(n) = 2⋅2⋅...⋅2 = 2ⁿ
bonus: The best theoretical implementation to fibonacci is actually a close formula, using the golden ratio:
(However, it suffers from precision errors in real life due to floating point arithmetics, which are not exact)
The recursion tree for fib(n) would be something like :
The O(2^n) complexity of Fibonacci number calculation only applies to the recursion approach. With a few extra space, you can achieve a much better performance with O(n).