Arrays & Hashing · Pattern 16 of 26
The Josephus elimination recurrence
n people in a circle, every k-th one leaves. Simulating is O(n·k). The survivor satisfies J(1) = 0 and J(n) = (J(n − 1) + k) mod n, which is O(n).
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- People in a circle removed every k-th step
- Only the last survivor is asked for
The template
int findTheWinner(int n, int k) {
int winner = 0; // 0-based survivor with 1 person
for (int size = 2; size <= n; size++)
winner = (winner + k) % size; // shift by k when one more person joins
return winner + 1; // 1-based answer
} def find_the_winner(n, k):
winner = 0 # 0-based survivor with 1 person
for size in range(2, n + 1):
winner = (winner + k) % size # shift by k when one more person joins
return winner + 1 # 1-based answer int findTheWinner(int n, int k) {
int winner = 0; // 0-based survivor with 1 person
for (int size = 2; size <= n; size++)
winner = (winner + k) % size; // shift by k when one more person joins
return winner + 1; // 1-based answer
} function findTheWinner(n, k) {
let winner = 0; // 0-based survivor with 1 person
for (let size = 2; size <= n; size++)
winner = (winner + k) % size; // shift by k when one more person joins
return winner + 1; // 1-based answer
} The variations
-
1The Josephus recurrence
After the first removal the circle restarts k places later with n − 1 people, so the survivor shifts by k each time the circle grows.
Mistakes to avoid
- Mixing 0-based and 1-based positions: compute 0-based, add 1 at the end.
Lesson done
Next: Greedy: make the safe choice now →Mark it done once you can write the template from memory and you have solved the worked examples yourself.