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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code