Find The First Player to win K Games in a Row - 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.

Input & Output

Example 1 — Basic Competition
$ Input: skills = [4,2,6,3,9], k = 3
Output: 4
💡 Note: Player 4 has the highest skill (9). After several games, player 4 reaches the front and wins 3 consecutive games, so return index 4.
Example 2 — Early Winner
$ Input: skills = [2,1,3], k = 1
Output: 0
💡 Note: Since k=1, we only need one win. Player 0 (skill=2) beats player 1 (skill=1) in the first game, so return index 0.
Example 3 — Small k Value
$ Input: skills = [1,9,8,2,3], k = 2
Output: 1
💡 Note: Player 1 (skill=9) beats player 0, then beats player 2. Two consecutive wins with k=2, so return index 1.

Constraints

  • n == skills.length
  • 2 ≤ n ≤ 105
  • 1 ≤ k ≤ 109
  • 1 ≤ skills[i] ≤ 106
  • All integers in skills are unique

Visualization

Tap to expand
First Player to Win K Games in a Row INPUT skills array (skill levels) 4 i=0 2 i=1 6 i=2 3 i=3 9 i=4 k = 3 Initial Queue Order 4 2 6 3 9 Front Player 9 (index 4) has highest skill level ALGORITHM STEPS 1 Initialize winner=0, wins=0 2 Compare Players First two in queue compete 3 Update Winner Higher skill wins, loser to end 4 Check K Wins Return if wins == k Simulation Trace Game 1: 4 vs 2 --> 4 wins (1) Game 2: 4 vs 6 --> 6 wins (1) Game 3: 6 vs 3 --> 6 wins (2) Game 4: 6 vs 9 --> 9 wins (1) Game 5: 9 vs 4 --> 9 wins (2) Game 6: 9 vs 2 --> 9 wins (3) OK FINAL RESULT Winning Player Skill: 9 Index: 4 Output 4 Player at index 4 (skill=9) won 3 consecutive games Win 1 Win 2 Win 3 Key Insight: Optimization: If k >= n-1, the player with maximum skill will eventually beat everyone. We only need to simulate until we find k consecutive wins OR the maximum element reaches front. Time Complexity: O(n) - each player is compared at most twice. Space: O(1) with deque optimization. TutorialsPoint - Find The First Player to win K Games in a Row | Optimized Simulation
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen