Find the Winner of an Array Game — LeetCode 1535 Python Solution

MediumArraySimulation
Problem
#1535
Reading time
3 min

The 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.

Example

Input
arr = [2,1,3,5,4,6,7], k = 2
Output
5
Explanation
Let's see the rounds of the game:

Python solution

Python
class Solution:
    def getWinner(self, arr: List[int], k: int) -> int:
        mx = arr[0]
        cnt = 0
        for x in arr[1:]:
            if mx < x:
                mx = x
                cnt = 1
            else:
                cnt += 1
            if cnt == k:
                break
        return mx

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 1535. Find the Winner of an Array Game?
LeetCode 1535. Find the Winner of an Array Game is rated Medium on LeetCode.
What is the time complexity of LeetCode 1535. Find the Winner of an Array Game?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 1535. Find the Winner of an Array Game?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1535. Find the Winner of an Array Game cover?
LeetCode 1535. Find the Winner of an Array Game is tagged Array and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview