Facebook Pixel

Josephus Problem

The Josephus Problem is a classic elimination game. There are n people standing in a circle, numbered from 0 to n-1. Starting from person 0, you count k people around the circle. The kth person is eliminated and leaves the circle. Then, continue counting k people from the next person, and eliminate the kth person. This continues until only one person remains. Find the position (0-indexed) of the last remaining person.

Input

  • n: an integer representing the number of people in the circle (1 ≤ n ≤ 500)
  • k: an integer representing the elimination count (1 ≤ k ≤ n)

Output

An integer representing the 0-indexed position of the winner (the last person remaining)

Examples

Example 1:

Input: n = 5, k = 2

Output: 2

Explanation:

  • Circle: [0, 1, 2, 3, 4]
  • Count 2 from 0: eliminate person 1 → [0, 2, 3, 4]
  • Count 2 from 2: eliminate person 3 → [0, 2, 4]
  • Count 2 from 4: eliminate person 0 → [2, 4]
  • Count 2 from 2: eliminate person 4 → [2]
  • Winner: person 2

Example 2:

Input: n = 6, k = 3

Output: 0

Explanation:

  • Circle: [0, 1, 2, 3, 4, 5]
  • Eliminations: 2 → 5 → 3 → 1 → 4
  • Winner: person 0

Example 3:

Input: n = 1, k = 1

Output: 0

Explanation: Only one person, so they win automatically

Try It Yourself

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro