Quant Memo
Core

The Josephus Problem

A classic elimination puzzle — people standing in a circle, every k-th one removed in turn — asking which position survives, and how to solve it with a simple recurrence instead of simulation.

Prerequisites: Induction and Recursive Structure in Puzzles

Picture nn people standing in a circle, numbered 1 through nn. Starting from person 1, you count off every kk-th person and remove them, continuing around the circle (skipping already-removed people) until only one survivor remains. The question: for given nn and kk, which starting position survives?

Simulating it directly — actually walking around a circle removing every kk-th person — works but is slow for large nn. The elegant approach uses a recurrence: if J(n)J(n) is the (0-indexed) surviving position among nn people counting by kk, then after the first removal you have n1n-1 people left, and the problem restarts on that smaller circle, just relabeled. The recurrence is J(1)=0J(1) = 0 and J(n)=(J(n1)+k)modnJ(n) = (J(n-1) + k) \bmod n for n>1n > 1. Each step solves the smaller problem, then maps its answer back onto the original numbering by shifting by kk positions and wrapping around with the modulus.

For example, with k=2k=2 (every second person eliminated) and n=5n=5 people: J(1)=0J(1)=0, J(2)=(0+2)mod2=0J(2)=(0+2)\bmod 2=0, J(3)=(0+2)mod3=2J(3)=(0+2)\bmod3=2, J(4)=(2+2)mod4=0J(4)=(2+2)\bmod4=0, J(5)=(0+2)mod5=2J(5)=(0+2)\bmod5=2. So the 0-indexed survivor is position 2, meaning person 3 (1-indexed) survives — which matches direct simulation: eliminating 2, 4, 1, 5 in order leaves 3.

The Josephus problem's survivor position follows the recurrence J(n)=(J(n1)+k)modnJ(n) = (J(n-1)+k) \bmod n starting from J(1)=0J(1)=0, letting you compute the answer in linear time instead of simulating the elimination round by round.

Related concepts

Practice in interviews

Further reading

  • Graham, Knuth, Patashnik, Concrete Mathematics, ch. 1
ShareTwitterLinkedIn