Find the Winner of an Array Game - Problem
Imagine a competitive tournament where players face off in head-to-head battles! You're given an integer array arr of distinct integers and an integer k.
The game works like this:
- ๐ฅ The first two elements
arr[0]andarr[1]compete - ๐ The larger number wins and stays at position 0
- ๐ค The smaller number moves to the end of the array
- ๐ This continues until one number wins
kconsecutive rounds
Your goal: Return the integer that will ultimately win the game.
Example: With arr = [2,1,3,5,4,6,7] and k = 2, the number 5 will win because it can defeat 2 consecutive opponents.
Input & Output
example_1.py โ Basic Game
$
Input:
arr = [2,1,3,5,4,6,7], k = 2
โบ
Output:
5
๐ก Note:
Game progression: [2,1,3,5,4,6,7] โ 2 beats 1 โ [2,3,5,4,6,7,1] โ 3 beats 2 โ [3,5,4,6,7,1,2] โ 5 beats 3 โ [5,4,6,7,1,2,3] โ 5 beats 4 โ 5 has won 2 consecutive rounds!
example_2.py โ Large k Value
$
Input:
arr = [3,2,1], k = 10
โบ
Output:
3
๐ก Note:
Since k=10 is larger than the array length, the maximum element (3) will definitely win. No matter how the game progresses, 3 will eventually reach the front and win forever.
example_3.py โ Immediate Winner
$
Input:
arr = [1,9,8,2,3], k = 3
โบ
Output:
9
๐ก Note:
Game: [1,9,8,2,3] โ 9 beats 1 โ [9,8,2,3,1] โ 9 beats 8 โ [9,2,3,1,8] โ 9 beats 2 โ 9 has won 3 consecutive rounds and is the winner!
Constraints
- 2 โค arr.length โค 105
- 1 โค arr[i] โค 106
- All integers in arr are distinct
- 1 โค k โค 109
- It is guaranteed that there will be a winner
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Line up all contestants with first two ready to compete
2
Battle
Current champion faces the next challenger
3
Victory
Winner stays as champion, loser goes to back of line
4
Count Wins
Track consecutive wins for current champion
5
Champion
Someone wins k battles in a row or maximum element takes over
Key Takeaway
๐ฏ Key Insight: The maximum element is the ultimate winner! We only need to check if anyone can achieve k consecutive wins before the max element reaches the front.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code