[LeetCode] Find the Losers of the Circular Game

2682. Find the Losers of the Circular Game

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. More formally, moving clockwise from the ith friend brings you to the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st friend.

The rules of the game are as follows:

1st friend receives the ball.

  • After that, 1st friend passes it to the friend who is k steps away from them in the clockwise direction.
  • After that, the friend who receives the ball should pass it to the friend who is 2 * k steps away from them in the clockwise direction.
  • After that, the friend who receives the ball should pass it to the friend who is 3 * k steps away from them in the clockwise direction, and so on and so forth.

In other words, on the ith turn, the friend holding the ball should pass it to the friend who is i * k steps away from them in the clockwise direction.

The game is finished when some friend receives the ball for the second time.

The losers of the game are friends who did not receive the ball in the entire game.

Given the number of friends, n, and an integer k, return the array answer, which contains the losers of the game in the ascending order.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> circularGameLosers(int n, int k) {
vector<int> A(n);
int p = 0, turn = 1;
while(true) {
if(A[p]) break;
A[p] = 1;
p = (p + turn * k) % n;
turn += 1;
}
vector<int> res;

for(int i = 0; i < n; i++) {
if(!A[i]) res.push_back(i+1);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/14/PS/LeetCode/find-the-losers-of-the-circular-game/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.