#2682

Find the Losers of the Circular Game

Easy
ArrayHash TableSimulationHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(n)

In the optimal solution, we use a set to track the friends who receive the ball and efficiently determine the losers in a single pass through the friends. This reduces unnecessary checks and speeds up the process.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a set to track received friends.
  2. 2Step 2: Start passing the ball according to the rules until a friend receives it for the second time.
  3. 3Step 3: Create a list of losers by checking which friends are not in the received set.
solution.py9 lines
1def findLosers(n, k):
2    received = set()
3    current = 0
4    i = 1
5    while current not in received:
6        received.add(current)
7        current = (current + i * k) % n
8        i += 1
9    return sorted(set(range(n)) - received)

Complexity note: The time complexity is O(n) because we pass the ball a maximum of n times before a friend receives it again, and we use a set to track received friends, which allows for O(1) average time complexity for insert and check operations.

  • 1The game is circular, so we need to use modulo to wrap around when passing the ball.
  • 2Tracking who has received the ball is crucial to determine the losers.

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