Posts Josephus Problem
Post
Cancel

Josephus Problem

PROBLEM DESCRIPTION

Given the total number of persons n and a number k which indicates that k-1 persons are skipped and kth person is killed in circle in a fixed direction. After each operation, the count will start from k+1th person. The task is to choose the safe place in the circle so that when you perform these operations starting from 1st place in the circle, you are the last one remaining and survive.

geeksforgeeks

SOLUTION

When k=2, refer to the below explanation:

snapshot

When k more than 2, we will need to make use of recursion. Good Explanation: Anuj YouTube

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution
{
   public int josephus(int n, int k)
    {
        return 1 + helper(n, k);
    }
    
    public int helper(int n, int k){
        if(n == 1) return 0;
        return (helper(n-1, k) + k)%n;
    }

}
This post is licensed under CC BY 4.0 by the author.