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] and arr[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 k consecutive 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
๐Ÿ† King of the Hill Tournament๐Ÿ‘‘CHAMPION5Challenger317Waiting in LineBATTLE!Game Rules1. Champion faces next challenger2. Larger number wins and becomes/stays champion3. Loser goes to the back of the line4. Game ends when someone wins k consecutive battles
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.
Asked in
Google 42 Facebook 35 Amazon 28 Microsoft 19
23.4K 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