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).

1 variation · 1 problem

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

Elimination Recurrence
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
}

The variations

  1. 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.
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.