#1535
Find the Winner of an Array Game
MediumArraySimulationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
In the optimal approach, we recognize that if k is greater than or equal to the length of the array, the maximum element will always win. Otherwise, we simulate the game but only keep track of the current winner and their win count, which allows us to avoid unnecessary comparisons.
⚙️
Algorithm
3 steps- 1Step 1: If k is greater than or equal to the length of the array, return the maximum element.
- 2Step 2: Initialize the winner and win count.
- 3Step 3: Iterate through the array, updating the winner and win count based on comparisons.
solution.py20 lines
1# Full working Python code
2
3def find_winner(arr, k):
4 if k >= len(arr):
5 return max(arr)
6 winner = arr[0]
7 win_count = 0
8 i = 1
9 while win_count < k:
10 if winner > arr[i]:
11 win_count += 1
12 i += 1
13 else:
14 win_count = 1
15 winner = arr[i]
16 i += 1
17 return winner
18
19# Example usage
20print(find_winner([2,1,3,5,4,6,7], 2)) # Output: 5ℹ
Complexity note: The time complexity is O(n) because we only need to iterate through the array once to find the winner, making it efficient even for larger inputs.
- 1If k is greater than or equal to the length of the array, the maximum element will always win.
- 2The game can be efficiently simulated by tracking only the current winner and their win count.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.