There are n
friends that are playing a game. The friends are sitting in a circle and are numbered from 1
to n
in clockwise order. More formally, moving clockwise from the i<sup>th</sup>
friend brings you to the (i+1)<sup>th</sup>
friend for 1 <= i < n
, and moving clockwise from the n<sup>th</sup>
friend brings you to the 1<sup>st</sup>
friend.
The rules of the game are as follows:
1<sup>st</sup>
friend.k
friends in the clockwise direction including the friend you started at. The counting wraps around the circle and may count some friends more than once.2
starting from the friend immediately clockwise of the friend who just lost and repeat.Given the number of friends, n
, and an integer k
, return the winner of the game.
For example, if n = 5
and k = 2
, the output should be 3
. Here's how the game unfolds:
Another example: if n = 6
and k = 5
, the output should be 1
. The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
The problem describes a game where n
friends are arranged in a circle, and every k
th friend is eliminated until only one winner remains. The task is to determine the winner.
A straightforward approach would be to simulate the game using a list or array to represent the circle of friends. We iterate through the list, removing friends according to the rules until only one friend remains. This method is easy to understand but can be inefficient for larger values of n
and k
.
def find_the_winner_naive(n: int, k: int) -> int:
friends = list(range(1, n + 1))
current_index = 0
while len(friends) > 1:
current_index = (current_index + k - 1) % len(friends)
friends.pop(current_index)
return friends[0]
# Example usage:
n = 5
k = 2
print(find_the_winner_naive(n, k))
# Output: 3
n = 6
k = 5
print(find_the_winner_naive(n, k))
# Output: 1
The problem is a variation of the Josephus Problem. The Josephus Problem has a recursive solution that can be implemented iteratively for better performance. The recursive relation is:
J(1, k) = 1
J(n, k) = (J(n - 1, k) + k - 1) % n + 1
This formula calculates the position of the winner directly without simulating the elimination process.
def find_the_winner(n: int, k: int) -> int:
winner = 1
for i in range(2, n + 1):
winner = (winner + k - 1) % i + 1
return winner
# Example usage:
n = 5
k = 2
print(find_the_winner(n, k))
# Output: 3
n = 6
k = 5
print(find_the_winner(n, k))
# Output: 1
pop
operation takes O(n) time.n
once, performing constant time operations within the loop.k
is 1, the friends are eliminated in order (1, 2, 3, ...).%
handles cases where k
is larger than n
.All these cases are handled correctly by the provided optimal solution. The iterative implementation also prevents stack overflow errors that might occur with a recursive approach for very large inputs.