#1823

Find the Winner of the Circular Game

Medium
ArrayMathRecursionQueueSimulationRecursionMathematical Induction
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

This approach uses a mathematical recursive formula known as the Josephus problem, which allows us to determine the winner without simulating the entire game. It significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a recursive function that returns the position of the winner for n friends and k steps.
  2. 2Step 2: Base case: if there's only one friend, they are the winner (return 0).
  3. 3Step 3: For more than one friend, calculate the winner's position recursively using the formula: (josephus(n - 1, k) + k) % n.
solution.py8 lines
1# Full working Python code
2
3def findTheWinner(n, k):
4    def josephus(n, k):
5        if n == 1:
6            return 0
7        return (josephus(n - 1, k) + k) % n
8    return josephus(n, k) + 1

Complexity note: The time complexity is O(n) due to the recursive calls, while the space complexity is O(1) as we only use a few variables for tracking.

  • 1Understanding the circular counting mechanism is crucial.
  • 2Recognizing the recursive nature of the problem can lead to a more efficient solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.