Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor.

Problem: Josephus problem: n people in a circle, every k-th person is eliminated; find the 1-based position of the survivor.
def josephus(n, k):
    pos = 0
    for m in range(2, n + 1):
        pos = (pos + k) % m
    return pos + 1
print(josephus(7, 3), josephus(10, 2))
What is printed?
  1. A. 7 5
  2. B. 4 9
  3. C. 3 5
  4. D. 4 5

Correct answer: D. 4 5

J(1) = 0 and J(m) = (J(m − 1) + k) mod m (0-based). For n = 7, k = 3 this gives position 4; for k = 2 the closed form 2(n − 2^⌊log₂ n⌋) + 1 = 2(10 − 8) + 1 = 5.

More Coding Interview Problems questions

Exams that ask this topic