Find the Winner of the Circular Game - Problem

Imagine n friends sitting in a circle playing an elimination game - this is the famous Josephus Problem! ๐ŸŽฏ

The friends are numbered 1 to n clockwise. Starting from friend 1, you count k friends clockwise (including your starting position). The k-th friend gets eliminated and leaves the circle.

Then, you start counting again from the next friend clockwise and repeat the process. This continues until only one winner remains.

Goal: Given n friends and step size k, determine which friend wins the game.

Example: With 5 friends and k=2, starting from friend 1, count 2 positions โ†’ eliminate friend 2, then start from friend 3, count 2 โ†’ eliminate friend 4, and so on.

Input & Output

example_1.py โ€” Python
$ Input: n = 5, k = 2
โ€บ Output: 3
๐Ÿ’ก Note: Friends are numbered 1,2,3,4,5. Start at 1, count 2 positions (1โ†’2), eliminate 2. Start at 3, count 2 (3โ†’4), eliminate 4. Start at 5, count 2 (5โ†’1), eliminate 1. Start at 3, count 2 (3โ†’5), eliminate 5. Friend 3 wins!
example_2.py โ€” Python
$ Input: n = 6, k = 5
โ€บ Output: 1
๐Ÿ’ก Note: With 6 friends and k=5, we eliminate every 5th person. Starting from friend 1, count 5 positions to eliminate friend 5, then continue the process. After all eliminations, friend 1 is the winner.
example_3.py โ€” Python
$ Input: n = 1, k = 1
โ€บ Output: 1
๐Ÿ’ก Note: Edge case: Only one friend in the circle, so friend 1 is automatically the winner.

Constraints

  • 1 โ‰ค n โ‰ค 500
  • 1 โ‰ค k โ‰ค n
  • n represents the number of friends in the circle
  • k represents the step size for counting

Visualization

Tap to expand
Josephus Problem: Find the Winner1234567Count k=3Mathematical Formula:J(n,k) = (J(n-1,k) + k) % n
Understanding the Visualization
1
Initial Circle
All n friends sit in a circle, numbered 1 to n clockwise
2
Start Counting
Begin at friend 1, count k positions clockwise
3
Eliminate Friend
The k-th friend leaves the circle
4
Continue Process
Start from next friend and repeat until one remains
5
Mathematical Pattern
The Josephus formula captures this pattern: J(n,k) = (J(n-1,k) + k) % n
Key Takeaway
๐ŸŽฏ Key Insight: The Josephus problem has an elegant mathematical solution that avoids simulation entirely. The recurrence relation J(n,k) = (J(n-1,k) + k) % n captures the pattern of how the winner's position changes as we add more people to the circle.
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
48.3K Views
Medium Frequency
~15 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen