![]() |
VOOZH | about |
There are n people standing in a circle, numbered from 1 to n. Starting from person 1, counting proceeds in clockwise direction. In each step, exactly k-1 people are skipped, and the k-th person is eliminated from the circle. The counting then resumes from the next person, and the process continues until only one person remains.
Determine the position of the last surviving person in the original circle.
Examples:
Input: n = 5, k = 2
Output: 3
Explanation: Firstly, the person at position 2 is killed, then the person at position 4 is killed, then the person at position 1 is killed. Finally, the person at position 5 is killed. So the person at position 3 survives.Input: n = 7, k = 3
Output: 4
Explanation: The persons at positions 3, 6, 2, 7, 5, and 1 are killed in order, and the person at position 4 survives.
Table of Content
We can store people in an array from 1 to n. Since counting is 0-based in the code, we use k-1 instead of k. Starting at index 0, in each step we remove the person at position: (index+(k-1)) % current size.
After removing, the recursive call continues from this new index with the reduced array. This process repeats until only one person remains, who is the survivor.
Illustration:
4
The idea is to use an array to mark alive people. Initially, all people are alive. Starting from the first person, we count k alive persons in the circle, skipping those already eliminated. When we reach the k-th alive person, we mark them as dead.
After each elimination, counting resumes from the next alive person. We continue this process iteratively, handling the circular nature by wrapping around the array indices, until only one person remains alive.
4
The Josephus problem can be solved recursively using the relation:
josephus(n,k) = (josephus(n−1,k)+k−1) % n + 1
The key idea is after each elimination, the circle shrinks, but the pattern of safe positions stays the same it’s just rotated. So if we know the safe position for n-1 people, we can shift it forward by k positions to get the safe position for n people. Repeat this shrinking-and-shifting idea until only 1 person remains, which is trivially safe.
Working:
4
We can solve this iteratively by building the solution from 1 person up to n.
4
Related Article: Josephus problem | Set 2 (A Simple Solution when k = 2)