Find the Winner of an Array Game - Problem
Given an integer array arr of distinct integers and an integer k.
A game will be played between the first two elements of the array (i.e. arr[0] and arr[1]). In each round of the game, we compare arr[0] with arr[1], the larger integer wins and remains at position 0, and the smaller integer moves to the end of the array. The game ends when an integer wins k consecutive rounds.
Return the integer which will win the game.
It is guaranteed that there will be a winner of the game.
Input & Output
Example 1 — Basic Case
$
Input:
arr = [2,1,3,5,4,6,7], k = 2
›
Output:
5
💡 Note:
Initially 2 is champion. 2 beats 1 (wins=1), then loses to 3. 3 becomes champion, loses to 5. 5 becomes champion, beats 4 (wins=1), beats 6 (wins=2). Since 5 gets k=2 consecutive wins, return 5.
Example 2 — Small k
$
Input:
arr = [3,2,1], k = 1
›
Output:
3
💡 Note:
3 starts as champion and immediately beats 2, achieving k=1 consecutive wins. Return 3.
Example 3 — Large k
$
Input:
arr = [1,9,8,2,3], k = 5
›
Output:
9
💡 Note:
Since k=5 >= n-1=4, the maximum element 9 will eventually become champion and stay there forever. Return 9.
Constraints
- 2 ≤ arr.length ≤ 105
- 1 ≤ k ≤ 109
- arr[i] is a distinct integer.
- 1 ≤ arr[i] ≤ 106
- It's guaranteed that there will be a winner of the game.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [2,1,3,5,4,6,7] and k=2 consecutive wins needed
2
Game Process
Elements compete, winner stays at front, loser goes to back
3
Output
First element to win k consecutive rounds
Key Takeaway
🎯 Key Insight: Track champions and consecutive wins efficiently, with optimization for large k values
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code