Find the Winner of the Circular Game
franklinqin0 DFSBacktracking
# Solution
# Simulation with Queue
Complexity
time:
space:
from collections import deque
class Solution:
def findTheWinner(self, n: int, k: int) -> int:
# init deque w/ n friends
circle = deque(range(1, n+1))
# perform eliminations while more than 1 player remains
while len(circle) > 1:
# process the 1st k-1 friends w/o eliminating them
for _ in range(k-1):
circle.append(circle.popleft())
circle.popleft()
return circle[0]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Recursion
Complexity
time:
space:
class Solution:
def winnerHelper(self, n, k):
if n == 1:
return 0
return (self.winnerHelper(n-1, k) + k) % n
def findTheWinner(self, n: int, k: int) -> int:
return 1 + self.winnerHelper(n, k)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Iteration
Complexity
time:
space:
class Solution:
def findTheWinner(self, n: int, k: int) -> int:
# return 1 + self.winnerHelper(n, k)
num = res = 0
while num < n:
num += 1
res = (res + k) % num
return res + 1
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9