Let's now write the space optimized tabulation approach for calculating fib of n.
Okay.
So let's get into it now initially itself, if n is less than or equal to one, we can just return n
itself.
So that would be pretty straightforward because we know that for n equal to zero, fib of zero is zero
itself, and for n is equal to one, fib of one is one itself.
Now, if that is not the case, as we have discussed in the previous video, we will need a few variables
pref.
Let's call it pref.
So prev would be equal to zero at this point.
And then we have cur for current and cur would be equal to one because zero and one are the first two
Fibonacci numbers.
And then we will also need a counter.
And initially counter can be set to one, because we know the values in the Fibonacci series up to n
is equal to one, right?
We know fib of zero and we know fib of one.
And that's why cur at this point is equal to one.
And the counter is also set to one.
Now we will need a while loop, and while counter less than n, it will keep going.
And when the counter becomes equal to n, it would mean that we have already calculated fib of n, and
that is why we come out of the while loop, and then we will just return whatever we are going to calculate.
So let me keep this blank for now.
So inside the while function we will calculate the next value in the Fibonacci expression or series
using the previous two values.
So I can say let.
Next is equal to prev plus curve okay.
And then because we have calculated the next value in the Fibonacci expression let me increment the
counter.
So counter plus is equal to one.
And then we move the prev and curr values by one step.
Because again we only need the latest two values to calculate the next value in the Fibonacci expression.
So I say prev is equal to cur and we can say cur is equal to next.
Okay.
And then we proceed again.
If counter is less than n we calculate the next value.
We increment the counter and we shift prev and curr by one position.
And we keep doing this.
And once counter becomes equal to n we will come out of this while loop.
And then we are over here.
And cur has the value of next.
So we will not be able to return next over here because next is defined inside the while loop.
So you cannot return next over here.
But that's not a problem because we are assigning the value of next to cur and we can just return cur
over here.
So cur would have the value of fib of n and we are returning that.
Now let's go ahead and run this code and see if it's passing all the test cases.
And you can see that it's passing all the test cases.