Find the Winner of the Circular Game - Problem

There are n friends sitting in a circle, numbered from 1 to n in clockwise order. The game follows these rules:

  • Start at friend 1
  • Count k friends clockwise (including the current friend)
  • The k-th friend is eliminated and leaves the circle
  • Continue from the next friend clockwise until only one remains

Given n friends and counting number k, return the position of the winner (the last remaining friend).

Input & Output

Example 1 — Basic Case
$ Input: n = 5, k = 2
Output: 3
💡 Note: Start at friend 1, count 2 friends clockwise (1→2), eliminate friend 2. Continue from friend 3, count 2 (3→4), eliminate friend 4. Process continues until friend 3 remains as winner.
Example 2 — Single Friend
$ Input: n = 1, k = 1
Output: 1
💡 Note: Only one friend in the circle, so friend 1 automatically wins the game.
Example 3 — Large Step Size
$ Input: n = 6, k = 5
Output: 1
💡 Note: With 6 friends and k=5, we count 5 positions each time. The elimination pattern results in friend 1 being the last remaining.

Constraints

  • 1 ≤ n ≤ 500
  • 1 ≤ k ≤ n

Visualization

Tap to expand
Find the Winner of the Circular Game INPUT 1 2 3 4 5 START clockwise n = 5 friends k = 2 count Queue: [1, 2, 3, 4, 5] 1 2 3 4 5 ALGORITHM STEPS 1 Initialize Queue Add 1 to n to queue 2 Count k-1 Friends Move front to back 3 Eliminate k-th Remove from queue 4 Repeat Until 1 Left Return last element Simulation (k=2) [1,2,3,4,5] --> elim 2 --> [3,4,5,1] [3,4,5,1] --> elim 4 --> [5,1,3] [5,1,3] --> elim 1 --> [3,5] [3,5] --> elim 5 --> [3] Order: 2, 4, 1, 5 Winner: 3 FINAL RESULT 1 2 3 4 5 Output: 3 Friend 3 is the winner! Elimination: 2 --> 4 --> 1 --> 5 OK - Verified Key Insight: Queue simulation models the circular game naturally. Move k-1 elements from front to back (counting), then remove the front element (elimination). Time: O(n*k), Space: O(n). Also known as Josephus Problem. TutorialsPoint - Find the Winner of the Circular Game | Queue-Based Simulation Approach
Asked in
Google 15 Microsoft 12 Amazon 10 Facebook 8
28.5K Views
Medium Frequency
~15 min Avg. Time
889 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