Problem Description
A competition involves n players, each with a unique skill level given in the skills array. Initially, the players are lined up in order. In each game, the first two players in the queue compete, and the player with the higher skill wins the game. The winner remains at the front with an incremented win streak while the loser is moved to the end of the queue. This process continues until a player wins k consecutive games. The task is to return the original index of the player who first reaches k consecutive wins.
Key Insights
- The simulation uses a queue to represent the order of players.
- In each round, compare the first two players; the higher skilled player wins.
- Maintain a counter for consecutive wins for the current leader.
- Once a player reaches k consecutive wins, they are declared the winner.
- Optimization: If k is large enough (k >= n - 1), the player with the maximum skill will eventually win, so directly return their index.
Space and Time Complexity
Time Complexity: O(n) in the optimal case with early termination when the max-skill player is reached; otherwise, O(n + k) in simulation. Space Complexity: O(n) due to the usage of a queue for simulation.
Solution
We simulate the competition using a queue (or similar data structure). At each step:
- Dequeue the first two players.
- Compare their skill levels.
- The winner (with the higher skill) remains (and has their win counter incremented), and the loser is enqueued at the back.
- If the win counter reaches k, the simulation stops and returns the winner’s original index.
- An early exit is applied if k is very large: the player with the maximum skill (who never loses once reached) will eventually win, so their index is returned immediately.
Code Solutions
Below are sample implementations in various languages: