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.

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
Because of the two recursive calls our stack grows very quickly and will take a long time for larger Fibonacci numbers...
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

But this solution only applies to Fibonacci...
How can we write a function that can take in any slow running function and give that function the ability to cache?

Writing a separate memoizer function
function memoizer(fun){
var cache = [];
// returns a version of the original function
// that is capable of caching its results
return function(n) {
var idx = n;
if(cache[idx] === undefined) {
cache[idx] = fun(n);
}
return cache[idx]
}
}

Solutions with comments:
Read more here Trasb.org
Memoization
By beelai88
Memoization
Technical interview problem to utilize memoization to improve the performance of the classic fibonacci function
- 731