There are n
friends playing a game, seated in a circle numbered 1 to n
clockwise. The game proceeds as follows:
k
friends clockwise (including the starting friend).Given n
and k
, return the winner.
Example 1:
n = 5
, k = 2
Output: 3
Explanation:
Example 2:
n = 6
, k = 5
Output: 1
Friends leave in this order: 5, 4, 6, 2, 3. Friend 1 is the winner.
Can you implement a function to efficiently determine the winner given n
and k
?
A straightforward approach is to simulate the game using a list (e.g., ArrayList in Java or a list in Python) to represent the circle of friends. We iterate through the list, removing elements based on the given k
value until only one friend remains. This simulates the exact process described in the problem statement.
n
, representing the friends.(current_index + k - 1) % list.size()
.import java.util.ArrayList;
import java.util.List;
class Solution {
public int findTheWinner(int n, int k) {
List<Integer> friends = new ArrayList<>();
for (int i = 1; i <= n; i++) {
friends.add(i);
}
int currentIndex = 0;
while (friends.size() > 1) {
currentIndex = (currentIndex + k - 1) % friends.size();
friends.remove(currentIndex);
}
return friends.get(0);
}
}
O(n*k) in the worst case. Because for n friends, we may have to traverse k positions in the list
O(n), because we store the initial n friends in a list.
The Josephus Problem is a classic mathematical puzzle that this problem is based on. It allows to solve the problem in O(n) time and O(1) space. The recursive formulation of the Josephus Problem is based on the following idea:
n-1
friends.The iterative approach exploits the property that the answer for n
friends can be derived from the answer for n-1
friends.
n
:
winner = (winner + k) % i
.winner + 1
(since the winner is 0-indexed).class Solution {
public int findTheWinner(int n, int k) {
int winner = 0;
for (int i = 1; i <= n; i++) {
winner = (winner + k) % i;
}
return winner + 1;
}
}
O(n), as we iterate from 1 to n
once.
O(1), as we only use a constant amount of extra space.
The optimal approach based on the Josephus Problem dramatically improves the efficiency of finding the winner. By leveraging the mathematical properties of the problem, we can reduce both the time and space complexity, making it suitable for larger inputs.