Let's now write the code for the memoization approach that we have discussed in the previous video for
solving the Fibonacci question.
All right.
So for this we will use a hash table.
So let's just call it memo.
And in memo I will initially itself add two key value pairs because we know that if n is equal to zero
then fib of n is zero.
And if n is equal to one, fib of one is one.
So we know these two cases.
So let's add that to the memo table.
Okay so I can say over here zero for zero it's zero.
And for one it's one.
All right.
Now we will need a helper function.
Let's just call it calculate fib okay.
And to this function we will be passing a number.
And it will return the Fibonacci of that particular number.
But let's write the details later.
And finally we will be just returning calculate fib and we will pass to it n, which is what we have
over here.
So this is the skeleton of the approach that we are going to take for this.
And inside the helper function, before we go ahead and calculate the Fibonacci number, we will check
whether we had already calculated it previously.
Okay.
So for that we will check whether the key num is present in memo or not.
So I can say if memo and num is not equal to undefined, because if it is not there, then it would
just num would be undefined.
So if memo and num is not equal to undefined, it means that we have already previously calculated this
and stored it in the hash table over here.
And in that case we don't need to recompute it, but rather we will just retrieve it and return it.
So I will say return memo at num okay.
So the value for this particular key in the hash table would be returned in this case.
But if this is not the case it means that we have not yet calculated and stored the Fibonacci for that
particular number in the hash table over here.
So we will go ahead and calculate it and store it at memo at num.
So I can say memo at num.
Is equal to calculate fib num minus one plus calculate fib num minus two.
Okay, so we have calculated the Fibonacci number for that particular num.
And we are storing it in the hash table over here.
And then we will just return memo at num.
All right.
So that's it.
Now let's go ahead and run this code and see if it's passing all the test cases.
All right.
You can see it's passing all the test cases.
So we have used a memoization object or a hash table over here.