Problem
A competition consists of n
players numbered from 0
to n - 1
.
You are given an integer array skills
of size n
and a positive integer
k
, where skills[i]
is the skill level of player i
. All integers in
skills
are unique.
All players are standing in a queue in order from player 0
to player n -1
.
The competition process is as follows:
- The first two players in the queue play a game, and the player with the higher skill level wins.
- After the game, the winner stays at the beginning of the queue, and the loser goes to the end of it.
The winner of the competition is the first player who wins k
games in a row.
Return the initial index of the winning player.
Examples
Example 1
|
|
Example 2
|
|
Constraints
n == skills.length
2 <= n <= 10^5
1 <= k <= 10^9
1 <= skills[i] <= 10^6
- All integers in
skills
are unique.
Solution
Method 1 – Simulation with Queue
Intuition
Simulate the process by keeping track of the current winner and their consecutive wins. The winner stays at the front, and the loser moves to the end. The first player to reach k consecutive wins is the answer.
Approach
- Initialize a queue with the player indices in order.
- Track the current winner and their consecutive win count.
- For each round:
- Compare the first two players in the queue by skill.
- The winner stays at the front, the loser goes to the end.
- If the winner is the same as the previous winner, increment their win count; otherwise, reset the count.
- If the win count reaches k, return the winner’s original index.
- If k >= n, the player with the highest skill will eventually win k times in a row.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + k)
, as each round processes at most one player to the end, and the winner is found in at most n + k steps. - 🧺 Space complexity:
O(n)
, for the queue.