Let's now get into the code for the approach that we have discussed in the previous video.
So basically we are going to use the answer to a smaller problem to solve the bigger problem.
So that's what we have discussed.
Right.
So again this is going to be a recursive solution.
So let's write the skeleton of the solution.
And then we'll go ahead and write the details of it okay.
Now we will need a helper function.
And let's just call that function Josephus itself.
Okay.
And to this function a particular value of n would be passed.
So let's call it n itself.
And finally we will have to call this function.
So that's Josephus and will be passing this value of n which is given to us over here.
And we will be getting back the index of the person who is the winner.
And because we typically don't start to count with zero, therefore over here we will have to add one
and this can be returned.
Okay.
So this is the skeleton of the solution.
And we have discussed this in detail in the previous video.
As in why we have to add one over here.
Now let's go ahead and write the details of the helper function.
So we will be writing the base case as well as the recursive case over here okay.
Now the base case will be the scenario where n is equal to one.
Now if there is just one person, then the self index position will be zero and we will be just returning
that.
So I can say if n is equal to one.
So if this is the case we will just return zero.
And over here when we get zero we will add one to it.
So which means that the first person is the safe person okay.
So that's done.
Now let's go ahead and take a look at the recursive case.
Now in the recursive case remember the approach that we are following over here is that we are using
the answer to a smaller problem to find the answer to the original problem.
So the answer to the smaller problem over here, when we are dealing with the problem of size n would
be Josephus n minus one.
Okay.
So that's the smaller problem.
So if we have this we have discussed that we just need to add k to this.
And then we'll have to do modulo n okay n is the size of the problem at this particular instance.
And this will give us the answer to the bigger problem okay.
So we will go ahead and return this.
So this is going to be the recursive case.
And that's it okay.
So notice we are using the solution to a smaller problem to arrive at the answer for a bigger problem.
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.
Now again do make use of the user logs.
They will help you debug your code in case you are stuck somewhere.