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
Find the Winner of an Array Game INPUT Array arr: 2 1 3 5 4 6 7 0 1 2 3 4 5 6 k = 2 Game Rules: Compare arr[0] vs arr[1] Winner stays at pos 0 Loser moves to end Win k times in a row to claim victory ALGORITHM STEPS 1 Round 1: 2 vs 1 2 wins (count=1) 2 Round 2: 2 vs 3 3 wins (count=1) 3 Round 3: 3 vs 5 5 wins (count=1) 4 Round 4: 5 vs 4 5 wins (count=2) Simulation Trace Round Fight Winner Wins 1 2 vs 1 2 1 2 2 vs 3 3 1 3 3 vs 5 5 1 4 5 vs 4 5 2 5 wins k=2 times! FINAL RESULT 5 WINNER Output: 5 Element 5 won 2 consecutive rounds (beats 4, then 6) OK - Verified Key Insight: Optimized Simulation: Track current winner and win count. If an element beats all others once, it's the max and will be the ultimate winner. No need to simulate beyond array length passes. Time Complexity: O(n) where n is array length. Space Complexity: O(1) - only tracking variables. TutorialsPoint - Find the Winner of an Array Game | Optimized Simulation Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Apple 6
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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