This coding challenge appeared in Leetcode April coding contest.
Caveats of this challenge
1. that index starts from 1
2. that cycle keeps chaning
I tried something like this but mine didn't pass the test, because I didn't take care of chaning cycle.
def findTheWinner(self, n: int, k: int) -> int: lst = list(range(1,n+1)) i = 1 while len(lst) < n: fr = i % k if fr == 0: fr = 5 try: lst.remove(i) except: pass i += k - 1
One elegant answer looks like this:
def findTheWinner(self, n: int, k: int) -> int: nums = [i for i in range(1, n + 1)] i = 0 while len(nums) != 1: i = (i + k - 1) % len(nums) nums.pop(i) return nums