Data structures · 8 / 15 Exercise Medium

The Josephus problem

Objective

Create a Python program that solves the Josephus problem with a double-ended queue (deque): n people stand in a circle and one in every k is eliminated until only one is left.

Instructions

  • Read one line with two integers n and k (with n ≥ 2, k ≥ 1). People are numbered from 1 to n and counting starts at person 1.
  • Count k people (the first is the one at the head of the circle) and eliminate the k-th; keep counting from the next person.
  • Show Elimination order: a b c ... with the eliminated numbers, separated by spaces, and Survivor: s with the number that survives.
  • Hint: deque.rotate(-(k - 1)) rotates the circle efficiently.
Input
7 3
Output
Elimination order: 3 6 2 7 5 1
Survivor: 4

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise