#3175
Find The First Player to win K Games in a Row
MediumApproaches
💡
Intuition
Time O(n²)Space O(1)
We can simulate the competition by repeatedly comparing the first two players in the queue. The winner stays at the front, and the loser goes to the back. We keep track of how many games the winner has won consecutively until one player wins k games in a row.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a queue with player indices and a variable to track consecutive wins.
- 2Step 2: While no player has won k games, compare the first two players in the queue.
- 3Step 3: Update the queue based on the winner and loser, and increment the win count for the winner.
solution.py30 lines
1from collections import deque
2
3def first_player_to_win_k_games(skills, k):
4 n = len(skills)
5 queue = deque(range(n))
6 consecutive_wins = 0
7 current_winner = None
8
9 while True:
10 player1 = queue.popleft()
11 player2 = queue.popleft()
12
13 if skills[player1] > skills[player2]:
14 winner = player1
15 loser = player2
16 else:
17 winner = player2
18 loser = player1
19
20 if current_winner == winner:
21 consecutive_wins += 1
22 else:
23 current_winner = winner
24 consecutive_wins = 1
25
26 if consecutive_wins == k:
27 return winner
28
29 queue.append(winner)
30 queue.append(loser)ℹ
Complexity note: The time complexity is O(n²) because in the worst case, we may have to simulate n games for each player, leading to n * n comparisons.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.