Leetcode 2682. Find the Losers of the Circular Game
You are given a circular game with n
players and a value k
. The players are sequentially numbered from 1 to n
, standing in a circle. Starting with player 1, every k-th player gets removed from the circle. After removing a player, the next player immediately to the removed player’s right continues the game. The process repeats until only one player remains.
You need to return a list of all players that lose the game in the order they were removed.
Example:
Input: n = 5, k = 2
Output: [2, 4, 1, 5]
Constraints:
1 <= n <= 100
1 <= k <= 100
n
and the step count k
always positive integers?
n
and k
are positive integers as given by the constraints.n
or k
is 1?
n = 1
, the list of losers would be empty since no one will be removed.import java.util.ArrayList;
import java.util.List;
public class CircularGameLosers {
public List<Integer> findLosers(int n, int k) {
List<Integer> players = new ArrayList<>();
for (int i = 1; i <= n; i++) {
players.add(i);
}
List<Integer> losers = new ArrayList<>();
int index = 0;
while (players.size() > 1) {
index = (index + k - 1) % players.size();
losers.add(players.remove(index));
}
return losers;
}
public static void main(String[] args) {
CircularGameLosers game = new CircularGameLosers();
System.out.println(game.findLosers(5, 2)); // Output: [2, 4, 1, 5]
}
}
n-1
players, each removal operation on an ArrayList (removing by index) takes O(n) time.n
.index
is used to keep track of the current position in the list.(index + k - 1) % players.size()
. This takes care of the circular nature.losers
list.players
list.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?