|
| 1 | +/** |
| 2 | + * 2682. Find the Losers of the Circular Game |
| 3 | + * https://leetcode.com/problems/find-the-losers-of-the-circular-game/ |
| 4 | + * Difficulty: Easy |
| 5 | + * |
| 6 | + * There are n friends that are playing a game. The friends are sitting in a circle and are numbered |
| 7 | + * from 1 to n in clockwise order. More formally, moving clockwise from the ith friend brings you to |
| 8 | + * the (i+1)th friend for 1 <= i < n, and moving clockwise from the nth friend brings you to the 1st |
| 9 | + * friend. |
| 10 | + * |
| 11 | + * The rules of the game are as follows: |
| 12 | + * |
| 13 | + * 1st friend receives the ball. |
| 14 | + * - After that, 1st friend passes it to the friend who is k steps away from them in the clockwise |
| 15 | + * direction. |
| 16 | + * - After that, the friend who receives the ball should pass it to the friend who is 2 * k steps |
| 17 | + * away from them in the clockwise direction. |
| 18 | + * - After that, the friend who receives the ball should pass it to the friend who is 3 * k steps |
| 19 | + * away from them in the clockwise direction, and so on and so forth. |
| 20 | + * |
| 21 | + * In other words, on the ith turn, the friend holding the ball should pass it to the friend who |
| 22 | + * is i * k steps away from them in the clockwise direction. |
| 23 | + * |
| 24 | + * The game is finished when some friend receives the ball for the second time. |
| 25 | + * |
| 26 | + * The losers of the game are friends who did not receive the ball in the entire game. |
| 27 | + * |
| 28 | + * Given the number of friends, n, and an integer k, return the array answer, which contains the |
| 29 | + * losers of the game in the ascending order. |
| 30 | + */ |
| 31 | + |
| 32 | +/** |
| 33 | + * @param {number} n |
| 34 | + * @param {number} k |
| 35 | + * @return {number[]} |
| 36 | + */ |
| 37 | +var circularGameLosers = function(n, k) { |
| 38 | + const visited = new Set(); |
| 39 | + let current = 0; |
| 40 | + let step = 1; |
| 41 | + |
| 42 | + while (!visited.has(current)) { |
| 43 | + visited.add(current); |
| 44 | + current = (current + step * k) % n; |
| 45 | + step++; |
| 46 | + } |
| 47 | + |
| 48 | + const result = []; |
| 49 | + for (let i = 0; i < n; i++) { |
| 50 | + if (!visited.has(i)) { |
| 51 | + result.push(i + 1); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return result; |
| 56 | +}; |
0 commit comments