Fibonacci Recursive Memoization
Updated: 01 February 2024
Base Implementation
Looking at the recursive Fibonacci implementation below:
The time complexity is and space complexity of
The above function gets extremely slow when n
is large due to the recursive implementation. For example asking for fib(50)
will have a time of
If we visualize the implementation of the above function we will see a tree, for example for n=7
:
Looking at the subtrees we can see that there is a lot of data that is frequently recalculated and we can try to memoize this data
With Memoization
We can create a memo object that we pass around that will allow us to access and early escape a calculation
And now running fib(50)
runs super quickly, this essentially takes the tree and collapses it into a more linear implementation and looks a bit like this:
Based on this, the time complexity is now without a relevant impact on the space complexity which is still