Find the Winner of the Circular Game — LeetCode 1823 Python Solution

MediumRecursionQueueArrayMathSimulation
Problem
#1823
Pattern
Stack
Reading time
2 min

The problem

There are n friends that are playing a game. The friends are sitting in a circle and are numbered from 1 to n in clockwise order.

Example

Input
n = 5, k = 2
Output
3
Explanation
Here are the steps of the game:

Python solution

Python
class Solution:
    def findTheWinner(self, n: int, k: int) -> int:
        if n == 1:
            return 1
        ans = (k + self.findTheWinner(n - 1, k)) % n
        return n if ans == 0 else ans

Complexity

MeasureComplexity
TimeO(V+E)
SpaceO(V) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1823. Find the Winner of the Circular Game is filed here because LeetCode tags it Queue, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1823. Find the Winner of the Circular Game?
LeetCode 1823. Find the Winner of the Circular Game is rated Medium on LeetCode.
What is the time complexity of LeetCode 1823. Find the Winner of the Circular Game?
The Python solution on this page runs in O(V+E).
What is the space complexity of LeetCode 1823. Find the Winner of the Circular Game?
The Python solution on this page uses O(V) auxiliary space.
What topics does LeetCode 1823. Find the Winner of the Circular Game cover?
LeetCode 1823. Find the Winner of the Circular Game is tagged Recursion, Queue, Array, Math 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