Leetcode 2682. Find the Losers of the Circular Game
In this task, you are given a circular game with n
participants numbered from 1
to n
. Initially, the game starts with the first player, and you have to determine who will be the losers.
You need to write a function that determines the list of players who will be out of the game based on the given rules. The function should return these losers in ascending order.
The rules are:
n
?Assumptions based on standard circular elimination games:
Here is a possible implementation in C++:
#include <iostream>
#include <vector>
std::vector<int> findLosers(int n) {
std::vector<int> losers;
std::vector<int> players(n);
// Initialize players
for (int i = 0; i < n; ++i) {
players[i] = i + 1;
}
int currentIndex = 0; // starts from the first player (index 0)
while (players.size() > 1) {
// computes the index of the player to be removed
currentIndex = (currentIndex + 1) % players.size();
losers.push_back(players[currentIndex]);
// remove the player from the game
players.erase(players.begin() + currentIndex);
// correct the currentIndex as currentIndex has shifted
if (currentIndex == players.size()) {
currentIndex = 0;
}
}
return losers;
}
int main() {
int n = 5;
std::vector<int> losers = findLosers(n);
std::cout << "The losers in ascending order are: ";
for (int loser : losers) {
std::cout << loser << " ";
}
std::cout << std::endl;
return 0;
}
players
to store the current players in the game and initialize it with player numbers from 1 to n
.currentIndex
to track the current position.currentIndex
to point correctly to the next player in a circular fashion.losers
vector.Therefore, the overall time complexity is O(n^2). This can be further optimized using a different data structure for efficient removal, but for standard implementations, this approach is simple and intuitive.
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?