In computer science and mathematics, the Josephus Problem (or Josephus permutation) is a theoretical problem. Following is the problem statement:
There are n people standing in a circle waiting to be executed. The counting out begins at some point in the circle and proceeds around the circle in a fixed direction. In each step, a certain number of people are skipped and the next person is executed. The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people are removed), until only the last person remains, who is given freedom. 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. The task is to choose the place in the initial circle so that you are the last one remaining and so survive.
For example, if n = 5 and k = 2, then the safe position is 3. Firstly, the person at position 2 is killed, then person at position 4 is killed, then person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives.
If n = 7 and k = 3, then the safe position is 4. The persons at positions 3, 6, 2, 7, 5, 1 are killed in order, and person at position 4 survives.
The problem has following recursive structure.
josephus(n, k) = (josephus(n - 1, k) + k-1) % n + 1 josephus(1, k) = 1
After the first person (kth from beginning) is killed, n-1 persons are left. So we call josephus(n – 1, k) to get the position with n-1 persons. But the position returned by josephus(n – 1, k) will consider the position starting from k%n + 1. So, we must make adjustments to the position returned by josephus(n – 1, k).
Following is simple recursive implementation of the Josephus problem. The implementation simply follows the recursive structure mentioned above.
The chosen place is 13
Time Complexity: O(n)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Josephus Problem Using Bit Magic
- Secretary Problem (A Optimal Stopping Problem)
- Find Cube Pairs | Set 1 (A n^(2/3) Solution)
- Find Cube Pairs | Set 2 (A n^(1/3) Solution)
- An interesting solution to get all prime numbers smaller than n
- Recursive solution to count substrings with same first and last characters
- Find Two Missing Numbers | Set 2 (XOR based solution)
- Minimum number of jumps to reach end | Set 2 (O(n) solution)
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Number of n digit stepping numbers | Space optimized solution
- Lucky alive person in a circle | Code Solution to sword puzzle
- Eggs dropping puzzle (Binomial Coefficient and Binary Search Solution)
- 21 Matchsticks Problem
- Tiling Problem
- Fibonacci problem (Value of Fib(N)*Fib(N) - Fib(N-1) * Fib(N+1))