Continuing, my 100-day DSA journey. I encountered a deadly problem. In this problem, the last survivor claims victory.
Like in the picture above, a group of friends, standing in a circle and one among them is holding a sword. The person with the sword moves in one particular direction and he kills the friend standing at a particular distance while skipping the friends in between him and the one he kills. And then he passes sword to the person standing next to the one he killed, then he goes back to his original position. Now, the person with the sword follows the footsteps of the first person carrying the sword and he kills his friend in the very same manner and hands the sword to the next person.
Let's try to understand this problem by code and one good youtube video: -
class Solution
{
public:
int solve(int n, int k){
if (n == 1){
return 0;
}
return (solve(n-1), k) + k)%n;
}
int josephus(int n, int k)
{
//Your code here
int ans = solve(n, k) + 1;
return ans;
}
};