R
E
A
C
T
O
xamples
epeat
ode
pproach
ptimize
est
{Memoization}
The First Question
Write a recursive solution to find the nth number in the Fibonacci sequence
What is the Fibonacci Sequence?
Fibonacci Sequence is 0, 1, 1, 2, 3, 5, 8, 13...
Mathematically Fn = Fn-1 + Fn-2
In words, each number in the sequence is the sum of the previous two integer values. The sequence is started with the numbers 0, 1.
*Bonus: This is an easy solution to the classic stair problem. Given n stairs, how many combinations exist if you can climb 1 or 2 stairs at a time.*
Example
fibonacci(7) // returns 13
Note, we start our Fibonacci Sequence at index 0, thus n=7 is 13. 0, 1, 1, 2, 3, 5, 8, 13...
function fibonacci(num){
if(num > 2) return fibonacci(num - 1) + fibonacci(num - 2);
else if(num <= 1) return num;
else return 1;
}
Solution to Part 1
The Second Question
That's great, but because of the two recursive calls our stack grows very quickly and will take a long time for larger Fibonacci numbers.
Even for the 42nd Fibonacci it takes several seconds. Much larger than that and REPL will actually time out. Check it out: REPL
The question: Use memoization to improve the efficiency of this Fibonacci Sequence
What is Memoization?
In computing, memoization is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.
In other words, we shall cache the results of our Fibonacci sequence as we find them. Rather than compute it each time, first we will check if we already have that Fibonacci number in our cache.
Solution to Part 2
var fibonacciTable = [0, 1, 1]
function fibonacci(num){
if(num > 2){
if(!fibonacciTable[num-1]) fibonacciTable[num-1] = fibonacci(num-1);
if(!fibonacciTable[num-2]) fibonacciTable[num-2] = fibonacci(num-2);
return fibonacciTable[num-1] + fibonacciTable[num-2];
}
else if(num <= 1) return num;
else return 1;
}
fibonacci(1000) //returns 4.346655768693743e+208 almost instantly
Solution with comments:
Read more here Trasb.org
Memoization
By pat310
Memoization
Technical interview problem to utilize memoization to improve the performance of the classic fibonacci function
- 2,183